You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重写虚函数遇‘looser exception specification’错误的原因与解决

重载std::exception的what()函数异常规范错误原因解析

问题场景

定义了模板Matrix类,并在内部实现了继承自std::exception的异常类:

template <typename T, int row, int col>
class Matrix{};

class MatrixException: public std::exception
{
private:
    const char* errmsg;
public:
    MatrixException(const char* msg="")
        :errmsg(msg) {} 
    const char* what() const {return errmsg;}
};

class IllegalOperation: public MatrixException
{
    public:
        IllegalOperation(const char* msg="")
            : MatrixException(msg) {}
};

在赋值运算符重载中抛出该异常时,编译器报错:

looser exception specification on overriding virtual function 'const char* Matrix<T, row, col>::MatrixException::what() const [with T = int; int row = 3; int col = 3]'

将what()函数修改为const char *what() const noexcept {return errmsg;}后,错误消失。

错误原因

C++规定,子类重写父类的虚函数时,子类函数的异常规范不能比父类更宽松:

  • 标准库中std::exception的what()函数,在C++11及后续标准中带有noexcept异常规范,明确表示该函数不会抛出任何异常。
  • 原代码中的what()函数未指定异常规范,默认等价于允许抛出任意异常,这比父类的noexcept规范宽松,违反了虚函数重写的规则,因此编译器抛出错误。
  • 添加noexcept后,子类what()函数的异常规范与父类严格一致,符合重写要求,错误自然解决。

内容的提问来源于stack exchange,提问作者Superot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 13:17:10