C++运行时获取类型信息的type_info类与bad_typeid异常

2020-01-06 14:22:19王旭

以下示例演示引发 bad_typeid 异常的 typeid 运算符。


// expre_bad_typeid.cpp
// compile with: /EHsc /GR
#include <typeinfo.h>
#include <iostream>

class A{
public:
  // object for class needs vtable
  // for RTTI
  virtual ~A();
};

using namespace std;
int main() {
A* a = NULL;

try {
  cout << typeid(*a).name() << endl; // Error condition
  }
catch (bad_typeid){
  cout << "Object is NULL" << endl;
  }
}

输出


Object is NULL


注:相关教程知识阅读请移步到C++教程频道。