C++覆盖异常::what()

我有一个自定义异常是

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()功能?提前致谢

回答

尝试这个

class RenterLimitException : public std::exception
{
public:
    const char* what() const noexcept;
};

const是函数签名的一部分。为了避免以后出现这种错误,你也可以养成使用override

class RenterLimitException : public std::exception
{
public:
    const char* what() const noexcept override;
};

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;
    }
}

请注意用于覆盖和捕获const异常的特定签名main(不是绝对必要的,但仍然是一个好主意)。特别要注意说明override符,它会导致编译器实际检查您指定的函数是否是基类提供的虚拟函数。

所述程序按预期打印:

No available copies.

  • Use `override` instead of `virtual`.
  • you should probably what to catch by const reference https://stackoverflow.com/questions/2145147/why-catch-an-exception-as-reference-to-const

以上是C++覆盖异常::what()的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>