bad_cast 异常
由于强制转换为引用类型失败,dynamic_cast
运算符引发 bad_cast 异常。
语法
catch (bad_cast)
statement
备注
bad_cast 的接口为:
class bad_cast : public exception
以下代码包含失败的 dynamic_cast
引发 bad_cast 异常的示例。
// expre_bad_cast_Exception.cpp
// compile with: /EHsc /GR
#include <typeinfo>
#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
:
Circle circle_instance;
Circle& ref_circle = circle_instance;
然后在 try
块中反转强制转换的意义,如下所示:
Shape& ref_shape = dynamic_cast<Shape&>(ref_circle);
成员
构造函数
构造函数 | 说明 |
---|---|
bad_cast | bad_cast 类型的对象的构造函数。 |
函数
函数 | 说明 |
---|---|
what | 待定 |
运算符
运算符 | 说明 |
---|---|
operator= | 用于将一个 bad_cast 对象赋予另一个对象的赋值运算符。 |
bad_cast
bad_cast
类型的对象的构造函数。
bad_cast(const char * _Message = "bad cast");
bad_cast(const bad_cast &);
operator=
用于将一个 bad_cast
对象赋予另一个对象的赋值运算符。
bad_cast& operator=(const bad_cast&) noexcept;
what
const char* what() const noexcept override;
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈