c++ typeid获取类型名-rtti

时间:2023-03-09 03:12:18
c++ typeid获取类型名-rtti

typeid操作符的作用就是获取一个表达式的类型。返回结果是const type_info&。不同编译器实现的type_info class各不相同。但c++标准保证它会实现一个name()方法,该方法返回类型名字的c-style字符串。

如果typeid的操作数不是类类型或者是没有虚函数的类,则typeid指出该操作数的静态类型。如果操作数是定义了至少一个虚函数的类类型,则在运行时计算类型。

c++ typeid获取类型名-rtti
// expre_typeid_Operator.cpp
// compile with: /GR /EHsc
#include <iostream>
#include <typeinfo.h> class Base
{
public:
virtual void vvfunc() {}
}; class Derived : public Base {}; using namespace std; int main()
{
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;
}
c++ typeid获取类型名-rtti

c++ RTTI还包括另外一个操作符dynamic_cast。有时间的时候,将c++ RTTI的知识整体梳理一下。