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:
        ...
    };
  • 相关阅读:
    QButton
    注入
    SpringBoot热重启配置
    centos7 安装 tomcat
    centos 安装jdk
    spring boot (6) AOP的使用
    spring boot (5) 自定义配置
    spring boot (4) 使用log4 打印日志
    SpringBoot (3)设置支持跨域请求
    spring boot (2) 配置swagger2核心配置 docket
  • 原文地址:https://www.cnblogs.com/chen-cai/p/10230347.html
Copyright © 2011-2022 走看看