一. 对于存在父子关系的类,当父亲指针指向孩子对象时,有时候需要确定具体指向那个孩子,那么可以用typeid函数确定,但是只能用于存在虚函数的继承层次里,例如:
#include <iostream>
#include <typeinfo.h>
using namespace std;
class one
{
class nested{};
nested* n;
public:
one()
{
n = new nested();
}
~one()
{
delete n;
}
nested* N()
{
return n;
}
};
int main()
{
one o;
cout << typeid(*o.N()).name() << endl;
system("pause");
return 0;
}
二. 通过RTTI可以确定指针类型,例如:
#include <iostream>
using namespace std;
class d1
{
public:
virtual void foo(){}
};
class d2
{
public:
virtual void bar(){}
};
class mi : public d1, public d2{};
class mi2 : public mi{};
int main()
{
d2* D2 = new mi2;
bool b1 = (typeid(D2) == typeid(mi2*));
bool b2 = (typeid(D2) == typeid(d2*));
cout << "b1=" << b1 << endl;
cout << "b2=" << b2 << endl;
system("pause");
return 0;
}
结果:
b1=0
b2=1
三. 运行时类型识别对于void*不起作用,例如:
#include <iostream>
#include <typeinfo>
using namespace std;
class strimpy
{
public:
virtual void happy(){}
virtual void joy(){}
};
int main()
{
void* v = new strimpy;
strimpy* s = dynamic_cast<strimpy*>(v); //error C2681: 'void *' : invalid expression type for dynamic_cast
cout << typeid(*v).name() << endl; //error C2100: illegal indirection
system("pause");
return 0;
}
四. 用模板来使用RTTI
#include <iostream>
#include <typeinfo>
using namespace std;
template<int id>
class announce
{
public:
announce()
{
cout << typeid(*this).name() << " constructor" << endl;
}
~announce()
{
cout << typeid(*this).name() << " destructor" << endl;
}
};
class x : public announce<0>
{
announce<1> m1;
announce<2> m2;
public:
x()
{
cout << "x::x()" << endl;
}
~x()
{
cout << "x::~x()" << endl;
}
};
int main()
{
x X;
system("pause");
return 0;
}
结果:
class announce<0> constructor
class announce<1> constructor
class announce<2> constructor
x::x()