[C++学习笔记15]RTTI

  1. RTTI
      runtime type information

  2. dynamic_cast运算符
      可以通过判断转换的成功与否来判断是否是该类型,用于有虚函数的向下转型。

  3. typeid运算符、type_info类
      
    类声明
        
      RTTI实例
    class Shape {
    public:
        virtual void draw() = 0;
        virtual ~Shape() =0 {}
    };
    
    class Circle : public Shape {
    public:
        void draw()
        {
            cout << "Circle::draw() ... " << endl;
        }
        ~Circle()
        {
            cout << "~Circle() ... " << endl;
        }
    };
    
    class Square : public Shape {
    public:
        void draw()
        {
            cout << "Square::draw() ... " << endl;
        }
        ~Square()
        {
            cout << "~Square() ... " << endl;
        }
    };
    
    int main(void)
    {
        Shape *p = nullptr;
        Circle c;
        p = &c;
    
        // 1.dynamic_cast<Circle *> 转换,运行时决定类型
        // 如果能转型成功,说明就是那种类型
        if (dynamic_cast<Circle *>(p))
            cout << "Circle" << endl;
        else if (dynamic_cast<Square *>(p))
            cout << "Square" << endl;
        else
            cout << "Other Type" << endl;
    
        // 2. 通过typeid运算符,返回一个type_info类对象,其中有个name方法
        // 注意其中=赋值运算符是private,所以不能直接赋值给type_info对象
        // 比如: type_info ti = typeid(Circle); // Error.
        cout << typeid(p).name() << endl; // class Shape *
        cout << typeid(*p).name() << endl; // class Circle
        cout << typeid(Circle).name() << endl; // class Circle
    
        // ()强制转换相对于reinterpret_cast来说,还是会做部分对齐
        if (typeid(*p).name() == typeid(Circle).name())
            ((Circle*)p)->draw();
        else if (typeid(*p).name() == typeid(Square).name())
            ((Square*)p)->draw();
        else
            cout << "No have this type" << endl;
        
        return 0;
    }
    main.cpp

     

转载于:https://www.cnblogs.com/ifpelset/articles/4544979.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值