RTTI概述
运行时类型识别,RTTI能够通过基类指针或引用检索该指针指向的对象的实际类型。
typeid运算符
typeid能够获得一个表达式的类型。
- 以下代码展示了typeid在解析多态类型时的行为。
Derived *pd = new Derived;
Base *pb = pd;
cout << typeid(pb).name() << endl; //prints "class Base *"
cout << typeid(*pb).name() << endl;//prints "class Derived"
cout << typeid(pd).name() << endl; //prints "class Derived *"
cout << typeid(*pd).name() << endl;//prints "class Derived"
delete pd;
如果表达式的类型是类类型且至少包含有一个虚函数,则typeid操作符返回表达式的动态类型,需要在运行时计算;否则,typeid操作符返回表达式的静态类型,在编译时就可以计算。