C++ RTTI

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:
    ...
};
posted @ 2019-01-06 21:00  c&z  阅读(148)  评论(0编辑  收藏  举报