zoukankan      html  css  js  c++  java
  • 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:
        ...
    };
  • 相关阅读:
    Jzoj5417 方阵
    Jzoj5414 幸运值
    PAT甲级——A1036 Boys vs Girls
    PAT甲级——A1035 Password
    PAT甲级——A1030 Travel Plan
    PAT甲级——A1026 Table Tennis
    PAT甲级——A1022 Digital Library
    PAT甲级——A1018 Public Bike Management
    PAT甲级——A1021 Deepest Root
    PAT甲级——A1020 Tree Traversals
  • 原文地址:https://www.cnblogs.com/chen-cai/p/10230347.html
Copyright © 2011-2022 走看看