c++语法3

接上篇继续学习多态、类型转换

多态:

多态(Polymorphism)按字面的意思就是“多种状态”。在面向对象语言中,接口的多种不同的实现方式即为多态
我们这里使用的模型是:人,英国人,中国人,都有吃饭的方法,人用手吃饭,英国人用刀叉,而中国人用筷子。我们问“这个人怎么吃饭的?”,应该根据其国别来回答,而不是简单地说“用手吃”。这就是多态。
在c++中多态是使用虚函数来实现的:

#include 
#include 
#include 
using namespace std;
class Human {
private:
    int a;
public:
      //定义虚函数
    virtual void eating(void) { cout<<"use hand to eat"<
类型转换

c中隐式类型转换是由编译器执行的:

#include 
int main(int argc, char **argv){
    double d = 100.1;
    int i = d;  // doubleתΪint
    char *str = "100ask.taobao.com";
    int *p = str; // char *תΪint * 
    printf("i = %d, str = 0x%x, p = 0x%x\n", i, str, p);
    return 0;
}

c中显示类型转换用()实现:

#include 
int main(int argc, char **argv){
    double d = 100.1;
    int i = d;  
    char *str = "100ask.taobao.com";
    int *p = (int *)str;
    printf("i = %d, str = 0x%x, p = 0x%x\n", i, (unsigned int)str, (unsigned int)p);
    return 0;
}

c++中使用reinterpret_cast()来实现转换:

#include 
int main(int argc, char **argv){
    double d = 100.1;
    int i = d;  
    char *str = "100ask.taobao.com";
    int *p = reinterpret_cast(str); 
    printf("i = %d, str = 0x%x, p = 0x%x\n", i, reinterpret_cast(str), reinterpret_cast(p));
    return 0;
}

reinterpret_cast相当于C中的小括号的类型转换。但是它不能转换带const的。
可以使用const_cast()去掉const属性再转换:

#include 
int main(int argc, char **argv){
    double d = 100.1;
    int i = d;  
    const char *str = "100ask.taobao.com";
    char *str2 = const_cast(str);
    int *p = reinterpret_cast(str2);
    printf("i = %d, str = 0x%x, p = 0x%x\n", i, reinterpret_cast(str), reinterpret_cast(p));
    return 0;
}

除此之外,C++还提供动态转换dynamic_cast(),但是只能用于含有虚函数类里面,因为它需要查找虚函数表来确定类的信息:

#include 
#include 
#include 
using namespace std;
class Human {
private:
    int a;
public:
    virtual void eating(void) { cout<<"use hand to eat"<(&h))
        cout<<"This human is Englishman"<(&h))
        cout<<"This human is Chinese"<

输出:

use hand to eat
use knife to eat
use chopsticks to eat
use hand to eat
use knife to eat
This human is Englishman
use chopsticks to eat
This human is Chinese
~Chinese()
~Human()
~Englishman()
~Human()
~Human()

这样我们就能再运行时确定多态的具体类型。
动态转换的格式:dynamic_cast < type-id > ( expression )
把expression转换成type-id类型的对象。
Type-id必须是类的指针、类的引用或者void *;
如果type-id是类指针类型,那么expression也必须是一个指针;
如果type-id是一个引用,那么expression也必须是一个引用。

动态类型是运行是转换,如果想在编译时转换可以使用格式:static_cast():

int main(int argc, char **argv){
    Human h;
    Guangximan g;
    Englishman *pe;
    //下行转换是可以的但不安全
    pe = static_cast(&h);
    //上行转换,但是不能转换成无关的Englishman类型,在编译时就报错,只能转换成相关的Chinese人
    Chinese *pc = static_cast(&g);
    return 0;
}

总结下静态转换:

  1. 用于类层次结构中基类和子类之间指针或引用的转换。
  2. 进行上行转换(把子类的指针或引用转换成基类表示)是安全的;
  3. 进行下行转换(把基类指针或引用转换成子类指针或引用)时,由于没有动态类型检查,所以是不安全的。

你可能感兴趣的:(c++语法3)