解析C++編程中的bad_cast異常。本站提示廣大學習愛好者:(解析C++編程中的bad_cast異常)文章只能為提供參考,不一定能成為您想要的結果。以下是解析C++編程中的bad_cast異常正文
因為強迫轉換為援用類型掉敗,dynamic_cast 運算符激發 bad_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();
};
以下代碼包括掉敗的 dynamic_cast 激發 bad_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();
}
}
因為強迫轉換的對象 (Shape) 不是派生自指定的強迫轉換類型 (Circle),是以激發異常。若要防止此異常,請將以下聲明添加到 main:
Circle circle_instance; Circle& ref_circle = circle_instance;
然後在 try 塊中反轉強迫轉換的意義,以下所示:
Shape& ref_shape = dynamic_cast<Shape&>(ref_circle);