注:本文基于vc编译器。
1)typeid的基本使用
- #include
- #include
- using namespace std;
-
- class A{};
- void help(int k) {
- string s1 = "", s2;
- getline(cin, s1);
- istringstream iss(s1);
- cout << "\//" << endl;//\转义
- }
-
- string s;
- int main()
- {
- cout <<"获取类名"<< typeid(A).name() << endl;
- cout << "获取函数类型" << typeid(help).name() << endl;
- cout << "获取变量类型" << typeid(s).name() << endl;
- return 0;
- }

2)typeid是一种运行时类型识别(RTTI)
参考自:C++ typeid关键字详解_CHENG Jian的博客-CSDN博客_c++ typeid
根据其运行时类型识别的特点,其可以识别出基类指针所指的派生类对象。
- #include
- #include
- using namespace std;
-
- class A{
- public:
- virtual void v(){}
- };
- class B:public A {
- public:
- void v() {}
- void v1(){}
- };
-
-
- const int s=1;
- int main()
- {
- A* a = new B();
- cout << "获取变量类型" << typeid(*a).name() << endl;
- return 0;
- }
![]()
3)但是直接用typeid打印变量时,const或者引用会被忽略掉
- int main()
- {
- const int &i = 0;
- cout << "获取变量类型" << typeid(s).name() << endl;
- return 0;
- }
![]()
这种情况可以参考:如何在C++中获得完整的类型名称_木头云的博客-CSDN博客_abi::__cxa_demangle
如何在C++中获得完整的类型名称_卡拉CC的博客-CSDN博客_c++ 获取类名称
这个时候需要自己去定义一些复杂的模板函数。
参考自:C++ 获取变量名称 & 获取类型的名称_sjhuangx的博客-CSDN博客_c++ 获取变量名
C/C++程序中获取变量的名称_幻想之渔的博客-CSDN博客_c++获取变量名称
本质上是用到了宏的#,#define varName(x) #x 即会将x转换成一个字符串。
- #include
- #include
- using namespace std;
-
- #define varName(x) #x
-
- int main()
- {
- const string s = "111";
- cout << "获取变量名" << varName(s) << endl;
- cout << "获取变量名" << typeid(varName(s)).name() << endl;
- return 0;
- }
