C++ 10 RTTI 运行时类型识别
2014-01-04 23:14
375 查看
来自:http://www.cppcourse.com/
01 dynamic_cast 安全的动态转型 需要运行时支持
用于运行时安全的向下转型 用于多态
02 typeid 返回一个 type_info对象
01 dynamic_cast 安全的动态转型 需要运行时支持
用于运行时安全的向下转型 用于多态
02 typeid 返回一个 type_info对象
#include <iostream> using namespace std; class Shape { public: virtual void Draw() = 0; virtual ~Shape() {} // 虚析构函数比较特殊 在抽象类中给出需要定义 }; class Circle : public Shape { public: void Draw() { cout << "Circle Draw ..." << endl; } }; class Square : public Shape { public: void Draw() { cout << "Square Draw ..." << endl; } }; int main(void) { Shape* p; Circle c; p = &c; p->Draw(); // 类型安全的向下转型 if (dynamic_cast<Circle*>(p)) // 如果能够转型说明 类型是Circle 运行时类型识别技术 { cout << "line: 40 p is point to a Circle object" << endl; Circle* cp = dynamic_cast<Circle*>(p); // 安全向下转型 cp->Draw(); } else if (dynamic_cast<Square*>(p)) { cout << "p is point to a Square object" << endl; } else { cout << "p is point to a Other object" << endl; } cout << typeid(*p).name() << endl; cout << typeid(Circle).name() << endl; if (typeid(Circle).name() == typeid(*p).name()) { cout << "#line 57 p is point to a Circle object" << endl; ((Circle*)p)->Draw(); } else if (typeid(Square).name() == typeid(*p).name()) { cout << "p is point to a Circle object" << endl; ((Square*)p)->Draw(); } else { cout << "p is point to a Other object" << endl; } return 0; }
相关文章推荐
- 【转载】C/C++杂记:运行时类型识别(RTTI)与动态类型转换原理
- c++ RTTI(运行时类型识别)
- C++杂记:运行时类型识别(RTTI)与动态类型转换原理
- C/C++杂记:运行时类型识别(RTTI)与动态类型转换原理
- RTTI C++ 运行时类型识别
- C++运行时类型识别RTTI
- C++运行时类型识别(RTTI)
- C++中的运行中动态类型识别RTTI
- C++ 运行时类型识别RTTI typeid<->dynamic_cast
- c++运行时类型识别(rtti)
- [c++ primer plus]RTTI运行阶段类型识别
- c++运行时类型识别(rtti)
- C++中的运行时类型识别(RTTI)
- The C++ Standard Library: RTTI(Run-Time Type Identification,运行时类型识别)
- c++ RTTI(运行时类型识别)
- c++模拟MFC中运行时类型识别(RTTI)(Run-Time Type Identification)
- C++学习之显式类型转换与运行时类型识别RTTI
- C++中的运行中动态类型识别RTTI
- C++学习之多态篇(运行时类型识别--RTTI(typeid和dynamic_cast))
- C++学习笔记之RTTI(运行时类型识别)