由于强制转换为引用类型失败,dynamic_cast 运算符引发 bad_cast 异常。
语法
| 1 2 |
catch (bad_cast)
statement
|
备注
bad_cast 的接口为:
| 1 2 3 4 5 6 |
class bad_cast : public exception {
public:
bad_cast(const char * _Message = "bad cast");
bad_cast(const bad_cast &);
virtual ~bad_cast();
};
|
以下代码包含失败的 dynamic_cast 引发 bad_cast 异常的示例。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// 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();
}
}
|
由于强制转换的对象 (Shape) 不是派生自指定的强制转换类型 (Circle),因此引发异常。若要避免此异常,请将下列声明添加到 main:
?| 1 2 |
Circle circle_instance;
Circle& ref_circle = circle_instance;
|
然后在 try 块中反转强制转换的意义,如下所示:
?| 1 |
Shape& ref_shape = dynamic_cast<Shape&>(ref_circle);
|








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。