RTTI
在了解 typeid 之前,先了解一下 RTTI (Run-Time Type Identification,运行时类型识别 ),它使程序能够获取由基指针或引用所指向的对象的实际派生类型,即允许“用指向基类的指针或引用来操作对象”的程序能够获取到“这些指针或引用所指对象”的实际派生类型。
typeid
typeid 是 c++ 的关键字之一,等同于 sizeof 这类的操作符。typeid 操作符的返回结果是名为 type_info 的标准库类型的对象的引用(在头文件typeinfo中定义)。
c++ 标准规定了必须实现如下四种运算:
t1 == t2 // 如果两个对象t1和t2类型相同,则返回true;否则返回false t1 != t2 // 如果两个对象t1和t2类型不同,则返回true;否则返回false t.name() // 返回类型的C-style字符串,类型名字用系统相关的方法产生 t1.before(t2) // 指出t1是否出现在t2之前,返回 bool 值
程序中创建type_info对象的唯一方法是使用typeid操作符 。type_info的name成员函数返回C-style的字符串,用来表示相应的类型名,但务必注意这个返回的类型名与程序中使用的相应类型名并不一定一致,这具体由编译器的实现所决定的,标准只要求实现为每个类型返回唯一的字符串。
代码示例
#include <iostream>
using namespace std;
class Base {
public:
virtual void vvfunc() {}
};
class Derived : public Base {
};
int main()
{
Derived* pd = new Derived;
Base* pb = pd;
cout << typeid(pb).name() << endl; // P4Base
cout << typeid(*pb).name() << endl; // 7Derived
cout << typeid(pd).name() << endl; // P7Derived
cout << typeid(*pd).name() << endl; // 7Derived
delete pd;
}