C++中"覆盖功能的异常规范比基本版本更宽松"的奇怪错误

Weird error on 'exception specification of overriding function is more lax than base version' in C++

本文关键字:错误 版本 范比基 覆盖 功能 异常 C++      更新时间:2023-10-16

做一个项目,我正在尝试创建一个包含一堆类的 HandleError 标头。在我的类BadNumber中,我有一个公共方法/函数,它接受字符串typenum。但是,当我尝试测试它时,我收到一个错误,要求exception specification of overriding function is more lax than base version因为我是从public std::exception继承的。我在谷歌上搜索了如何解决这个问题,它建议我在what()中对此异常调用进行 noexcept 覆盖调用(链接在这里(。该示例几乎与我的相同,但具有相同的错误消息。

代码(使用 GCC/Clang c++11 编译(:

#include <exception>
#include <string>
class BadNumber : public std::exception
{
private:
std::string _msg;
public:
BadNumber(std::string type, std::string num) : _msg(num + "is invalid type for " + type) {}
const char *what() const noexcept override
{
return (_msg.c_str());
}
};

错误信息:

src/../inc/HandleError.hpp:23:15: error: exception specification of overriding function is more lax than base version
const char *what() const noexcept override
^
/Library/Developer/CommandLineTools/usr/include/c++/v1/exception:102:25: note: overridden virtual function is here
virtual const char* what() const _NOEXCEPT;

我按照要求做了一些研究,但仍然没有运气,仍然做得更多。非常感谢您的帮助,获得一些反馈和建设性总是有帮助的。感谢您的时间和耐心:)

所以我意识到我必须将每个类作为虚拟析构函数,否则,我会使用我不想这样做的基本析构函数。这是我的解决方案:

class BadNumber : public std::exception
{
private:
std::string _msg;
public:
virtual ~BadNumber() throw() {return ;}
BadNumber(std::string type, std::string num) : _msg(num + "is invalid type for " + type) {}
virtual const char *what() const throw()
{
return (_msg.c_str());
}
};