bad_cast 例外狀況
運算子 會擲回 dynamic_cast
bad_cast 例外狀況,因為無法轉換成參考型別。
語法
catch (bad_cast)
statement
備註
bad_cast 的 介面為:
class bad_cast : public exception
下列程式碼包含擲回 bad_cast 例外狀況失敗 dynamic_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;