c++ - 尝试在 C++ 中实现异常时出错

标签 c++ exception

error: declaration of 'virtual const char* numberOutOfBounds::what() const' has a different exception specifier

我一直在寻找解决方案,但找不到我做错了什么。

我的头文件中的异常:

class FileException:public exception {
public:
    virtual const char* what() const throw();
};

class numberOutOfBounds:public exception {
public:
    virtual const char* what() const throw();
};

以及我的 cpp 文件中的异常(exception)情况:

const char* FileException::what() const {
    return "Cannot open file";
}

const char* numberOutOfBounds::what() const {
    return "illegal number entered";
}

有人可以让我知道我在这里做错了什么吗? 我环顾四周,无法弄清楚为什么我会收到我收到的错误消息。

最佳答案

virtual const char* what() const throw();

此函数声明有一个 throw 声明,但定义中缺少它。

你需要:

const char* FileException::what() const throw() {
                                     // ^^^^^^^ - added
    return "Cannot open file";
}

仅供引用,已经有一个 std::out_of_range 异常类。

关于c++ - 尝试在 C++ 中实现异常时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33029384/

相关文章:

c++ - 将变量数据发送到其他类时出现问题

java - 从 ADT 模拟器报告堆栈跟踪

c++ - 一个简单类模板的c++17中的 friend 流运算符

c++ - CImg 库中的奇怪语法,不知道它叫什么

ruby - $之间的区别!与救援变量

c# - 阶乘函数 - 设计和测试

Xamarin随机集合异常修改

PHP:尝试/捕获失败

c++ - 指针访问或引用访问哪个更快?

c++ - cuda __syncthreads() 在我的代码中不起作用