- RTTI
runtime type information
- dynamic_cast运算符
可以通过判断转换的成功与否来判断是否是该类型,用于有虚函数的向下转型。
- 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; }
转载于:https://www.cnblogs.com/ifpelset/articles/4544979.html