我已经创建了我自己的异常类,它派生自 runtime_error
并在 c'tor 中获取一个 int。
我想为这个异常创建一个基类,以便使用多态性,所以我只能捕获基类,基本上我会捕获派生类,然后从中调用 .what() 方法。
所以,这是基类:(ofc 在另一个 cpp 文件中我得到了 baseException::~baseException(){})
class baseException
{
virtual ~baseException()=0 {}
virtual const char* what()=0;
};
这是派生类:
class myException: public runtime_error, public baseException
{
public:
myException(int): runtime_error("Error occured") {}
const char* what() {return runtime_error::what();}
};
但是当我主要写的时候:
catch(baseException* x)
{
cout<<x->what();
}
它只是跳过它而不进入 block ,即使 myException 继承自 baseException。有什么建议吗?
最佳答案
您应该通过引用(或 const 引用)捕获异常,而不是通过指针。
关于c++ - 异常中的虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11083421/