我有一个自定义异常是
class RenterLimitException : public std::exception
{
public:
const char* what();
};
Run Code Online (Sandbox Code Playgroud)
覆盖 what() 的正确方法是什么?现在,我在头文件中创建了这个自定义,并希望覆盖我的 cpp 文件中的 what()。我的功能定义如下:
const char* RenterLimitException::what(){
return "No available copies.";
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用我的 try/catch 块时,它不会打印我给函数 what() 的消息,而是打印std::exception
我的 try/catch 块是这样的:
try{
if (something){
throw RenterLimitException();}
}
catch(std::exception& myCustomException){
std::cout << myCustomException.what() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
是因为我的 try/catch 块还是我的what()
功能?提前致谢
尝试这个
class RenterLimitException : public std::exception
{
public:
const char* what() const noexcept;
};
Run Code Online (Sandbox Code Playgroud)
const
是函数签名的一部分。为了避免以后出现这种错误,你也可以养成使用override
class RenterLimitException : public std::exception
{
public:
const char* what() const noexcept override;
};
Run Code Online (Sandbox Code Playgroud)
override
如果你得到一个错误的虚函数签名,会给你一个错误。
这不是该what
方法的正确签名,您应该按照const char * what() const noexcept override
以下完整程序使用:
#include <iostream>
class RenterLimitException : public std::exception {
public:
const char * what() const noexcept override {
return "No available copies.";
}
};
int main() {
try {
throw RenterLimitException();
} catch (const std::exception& myCustomException) {
std::cout << myCustomException.what() << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意用于覆盖和捕获const
异常的特定签名main
(不是绝对必要的,但仍然是一个好主意)。特别要注意说明override
符,它会导致编译器实际检查您指定的函数是否是基类提供的虚拟函数。
所述程序按预期打印:
No available copies.
Run Code Online (Sandbox Code Playgroud)