什么是bad_cast异常?

当对引用类型的动态转换未通过运行时检查(例如,因为类型与继承无关)时,将引发此类型的异常。

继承关系

class bad_cast : public exception

例子:

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

classShape {public:virtual void virtualfunc() const{}
};
class Circle: publicShape {public:virtual void virtualfunc() const{}
};
using namespacestd;intmain() {
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();
}
}

标签: none

添加新评论