码迷,mamicode.com
首页 > 编程语言 > 详细

C++ RTTI

时间:2019-01-06 22:01:04      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:tor   引用   info   int   rtti   数据   char   plane   地址   

RTTI:(Run-Time Type Identification,运行时类型识别)

class Flyable
{
public:
    virtual void take_off() = 0;
    virtual void land() = 0;
};

class Bird : public Flyable
{
public:
    void foraging()
    {
        cout << "bird foraging" << endl;
    }
    virtual void take_off()
    {
        cout << "bird take off" << endl;
    }
    virtual void land()
    {
        cout << "bird land" << endl;
    }
};

class Plane : public Flyable
{
public:
    void carry()
    {
        cout << "plane carry" << endl;
    }
    virtual void take_off()
    {
        cout << "plane take off" << endl;
    }
    virtual void land()
    {
        cout << "plane land" << endl;
    }
};

void do_something(Flyable* obj)
{
    obj->take_off();
    cout << typeid(*obj).name() << endl;
    if (typeid(*obj) == typeid(Bird))
    {
        Bird* pBird = dynamic_cast<Bird*>(obj);
        if (pBird != nullptr) {
            pBird->foraging();
        }
    }
    obj->land();
}

int main()
{
    Flyable* pFlyable = new Bird();
    do_something(pFlyable);

    return 0;
}

dynamic_cast 使用注意事项:

(1)只能应用于指针和引用的转换

(2)要转换的类型中必须包含虚函数

(3)转换成功返回子类的地址,识别返回NULL

typeid 使用注意事项

(1)typeid 返回一个type_info 对象的引用

(2)如果想通过基类的指针获得派生类的数据类型,基类必须带有虚函数

(3)只能获取对象的实际类型

type_info 的源码:

class type_info
{
public:
    const char* name() const;
    bool operator==(const type_info& rhs) const;
    bool operator!=(const type_info& rhs) const;
    int before(const type_info& rhs) const;
    virtual ~type_info();
private:
    ...
};

C++ RTTI

标签:tor   引用   info   int   rtti   数据   char   plane   地址   

原文地址:https://www.cnblogs.com/chen-cai/p/10230347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!