typeid用户检查表达式的类型。
typeid (expression)
typeid返回定义在标准头文件中常对象类型的引用,且返回值是可通过==和!=比较的.获得的对象可通过name()成员获取以空格结尾的数据类型或类名字符串。
#include <iostream>
#include <typeinfo>
using namespace std;
int main () {
int * a,b;
a=0; b=0;
if (typeid(a) != typeid(b))
{
cout << "a and b are of different types:/n";
cout << "a is: " << typeid(a).name() << '/n';
cout << "b is: " << typeid(b).name() << '/n';
}
return 0;
}
typeid使用RTTI跟踪动态对象的类型在typeid运用于类时。当typeid运用于类型为多态的类,将返回最底层对象的类型。
#include <iostream>
#include <typeinfo>
#include <exception>
using namespace std;
class CBase { virtual void f(){} };
class CDerived : public CBase {};
int main () {
try {
CBase* a = new CBase;
CBase* b = new CDerived;
cout << "a is: " << typeid(a).name() << '/n';
cout << "b is: " << typeid(b).name() << '/n';
cout << "*a is: " << typeid(*a).name() << '/n';
cout << "*b is: " << typeid(*b).name() << '/n';
} catch (exception& e) { cout << "Exception: " << e.what() << endl; }
return 0;
}