66-C++中的类型识别

来源:互联网 发布:core keygen for mac 编辑:程序博客网 时间:2024/06/06 10:50

1、类型识别

这里写图片描述

p指针指向父类对象,根据赋值性原则,父类指向一个子类对象也是合法的。现在p指针指向一个子类对象,可以说指针p的静态类型为Base*(p的本意是指向一个父类对象的,)静态类型是指针指向期望的类型,然而由于赋值兼容性原则,p指向子类的类型,这是指针p所指向的对象为动态类型,动态类型与期望类型有可能是不一样的,r的本意是作为父类对象的别名,但是由于赋值兼容性原则它可以作为一个子类的别名来使用,没有办法判断它是作为父类对象的别名还是子类对象的别名来使用。

2、静态类型和动态类型

这里写图片描述

3、问题

这里写图片描述

4、动态类型识别

这里写图片描述

#include <iostream>#include <string>using namespace std;class Base{public:    virtual string type()    {        return "Base";    }};class Derived : public Base{public:    string type()    {        return "Derived";    }    void printf()    {        cout << "I'm a Derived." << endl;    }};class Child : public Base{public:    string type()    {        return "Child";    }};void test(Base* b){    /* 危险的转换方式 */    // Derived* d = static_cast<Derived*>(b);    if( b->type() == "Derived" )//通过多态判断当前对象返回的类型,进行相应的强制类型转换    {        Derived* d = static_cast<Derived*>(b);        d->printf();    }    //cout << dynamic_cast<Derived*>(b) << endl;//这种方法 转换不成功 输出0;}int main(int argc, char *argv[]){    Base b;    Derived d;    Child c;    test(&b);    test(&d);    test(&c);    return 0;}0I'm a Derived.0x7ffed91f54400

5、缺陷

这里写图片描述

6、类型识别关键字

这里写图片描述

7、关键字使用

这里写图片描述

8、注意事项

这里写图片描述

#include <iostream>#include <string>#include <typeinfo>using namespace std;class Base{public:    virtual ~Base()    {    }};class Derived : public Base{public:    void printf()    {        cout << "I'm a Derived." << endl;    }};void test(Base* b){    const type_info& tb = typeid(*b);    cout << tb.name() << endl;}int main(int argc, char *argv[]){    int i = 0;    const type_info& tiv = typeid(i);    const type_info& tii = typeid(int);    cout << (tiv == tii) << endl;    Base b;    Derived d;    test(&b);    test(&d);    return 0;}14Base7Derived//注意 typeid在不同的编译器下,返回的类型名是不一样的

9、小结

这里写图片描述

原创粉丝点击