1 用法 typeinfo(类名) typeinfo(对象)
2 要使用#include <typeinfo>
3 需要虚函数才可以使用RTTI ,才可以使用dymnaic_cast()<> 和 typeid()
4 typeinfo的几个接口 name() == != before()
#include <iostream>
#include <typeinfo> //使用typeinfo的头文件
using namespace std;
class A
{
public:
virtual void f(){} //需要有虚函数 才可以用RTTi
};
class B: public A{};
class C:public A{};
class D:public A{};
int main()
{
cout << typeid(A).name() <<endl; //1A
cout << typeid(C).name() <<endl; //1C
A *p1 = new A,*p2 = new B ,*p3 =new C,*p4 = new D,*p5 = new B ;
//指针都是A*类型的 但还是可以识别出来
//typeid 返回type_info对象
// 接口 name() 函数 返回类型名字
cout << typeid(*p1).name() <<endl; //1A (LINUX下) //class A(vs2010下)
cout << typeid(*p2).name() <<endl; //1B //class B
cout << typeid(*p3).name() <<endl;//1C //class C
// == 比较类型是否相等 true 相等 false 不相等
cout << (typeid(*p2) == typeid(*p5)) <<endl;
cout << (typeid(*p2) != typeid(*p5)) <<endl;
//LINUX GCC 下是这样的 before() 对象是参数的父类或者同类时 返回0 是参数的子类时返回1
//VS2010下实验的结果是 p1是p4父类时返回1 否则返回0
cout << typeid(*p1).before(typeid(*p4)) <<endl;
}