运行时类型信息 (RTTI)
dynamic_cast
- 用于多态类型的转换
typeid
- typeid 运算符允许在运行时确定对象的类型
- type_id 返回一个 type_info 对象的引用
- 如果想通过基类的指针获得派生类的数据类型,基类必须带有虚函数
- 只能获取对象的实际类型
type_info
- type_info 类描述编译器在程序中生成的类型信息。 此类的对象可以有效存储指向类型的名称的指针。 type_info 类还可存储适合比较两个类型是否相等或比较其排列顺序的编码值。 类型的编码规则和排列顺序是未指定的,并且可能因程序而异。
- 头文件:
typeinfo
typeid、type_info 使用
class Flyable // 能飞的{public:virtual void takeoff() = 0; // 起飞virtual void land() = 0; // 降落};class Bird : public Flyable // 鸟{public:void foraging() {...} // 觅食virtual void takeoff() {...}virtual void land() {...}};class Plane : public Flyable // 飞机{public:void carry() {...} // 运输virtual void take off() {...}virtual void land() {...}};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:...};class doSomething(Flyable *obj) // 做些事情{obj->takeoff();cout << typeid(*obj).name() << endl; // 输出传入对象类型("class Bird" or "class Plane")if(typeid(*obj) == typeid(Bird)) // 判断对象类型{Bird *bird = dynamic_cast<Bird *>(obj); // 对象转化bird->foraging();}obj->land();};
