# typeid().name() typeid().name()是一个工具函数,可以返回对象或者表达式的类型,该函数位于头文件 `` 中,所以需要包含。typeid()接受一个对象或者表达式,返回一个名为type_info的标准库类型的对象的应用,type_info中存储了特定类型的有关信息。typeid().name()以c-style字符串形式返回类型名。typeid()其实是一个单目操作符。 ```c++ #include #include using namespace std; class Class1{}; class Class2:public Class1{}; void fn0(); int fn1(int n); int main(void) { int a = 10; int* b = &a; float c; double d; cout << typeid(a).name() << endl; cout << typeid(b).name() << endl; cout << typeid(c).name() << endl; cout << typeid(d).name() << endl; cout << typeid(Class1).name() << endl; cout << typeid(Class2).name() << endl; cout << typeid(fn0).name() << endl; cout << typeid(fn1).name() << endl; cout << typeid(typeid(a).name()).name() << endl; system("pause"); } ``` typeid().name()可以返回变量、函数、类的数据类型名,功能相当强大的。`cout << typeid(typeid(a).name()).name() << endl;`可以看到结果为`char const *`,因此typeid().name()返回了存储类型名的字符串。 在编译程序时需要注意,使用MSVC和GCC编译后程序运行的结果有所不同。如果我们使用MSVC编译,那么输出的名称都是完整的名称,结果如下: ```bash int int * float double class std::basic_string,class std::allocator > bool char short char const * ``` 如果使用的是GCC编译的结果,那么输出的名称都是缩写的名称,结果如下: ```bash i Pi f d NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE ```