【发布时间】:2021-02-22 10:03:00
【问题描述】:
我有一个自定义异常
class RenterLimitException : public std::exception
{
public:
const char* what();
};
覆盖what() 的正确方法是什么?现在,我在头文件中创建了这个自定义,并希望覆盖我的 cpp 文件中的 what()。 我的功能定义如下:
const char* RenterLimitException::what(){
return "No available copies.";
}
但是,当我使用 try/catch 块时,它不会打印我给函数 what() 的消息,而是打印 std::exception
我的 try/catch 块是这样的:
try{
if (something){
throw RenterLimitException();}
}
catch(std::exception& myCustomException){
std::cout << myCustomException.what() << std::endl;
}
是因为我的 try/catch 块还是我的 what() 函数?
提前致谢
【问题讨论】:
-
您的
what方法具有wrong signature。 -
@G.M.所以应该是
virtual const char* RenterLimitException::what() const throw(){ return "No available copies."; }? -
一般来说,您应该使用
override关键字,它会警告您您的实现不会覆盖基类中的what()方法。 -
在现代 C++ 中,使用
noexcept说明符而不是已弃用的throw()异常说明。