bad_cast异常

由于对引用类型,将会失败的转换 bad_cast 异常。 dynamic_cast 运算符引发。

catch (bad_cast)
   statement

备注

bad_cast 的接口是:

class bad_cast : public exception {
public:
   bad_cast(const char * _Message = "bad cast");
   bad_cast(const bad_cast &);
   virtual ~bad_cast();
};

下面的代码包含引发 bad_cast 异常失败的 dynamic_cast 的示例。

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

class Shape {
public:
   virtual void virtualfunc() const {}
};

class Circle: public Shape {
public:
   virtual void virtualfunc() const {}
};

using namespace std;
int main() {
   Shape shape_instance;
   Shape& ref_shape = shape_instance;
   try {
      Circle& ref_circle = dynamic_cast<Circle&>(ref_shape); 
   }
   catch (bad_cast b) {
      cout << "Caught: " << b.what();
   }
}

引发异常,因为被转换的对象 (形状) 从指定的转换类型 (圆圈) 未派生。 若要避免异常,添加以下声明添加到 main:

   Circle circle_instance;
   Circle& ref_circle = circle_instance;

然后反转转换的含义在 try 的块如下所示:

   Shape& ref_shape = dynamic_cast<Shape&>(ref_circle);

请参见

参考

dynamic_cast运算符

C++关键字

C++异常处理