【问题标题】:Getting an error while deriving class from std::exception从 std::exception 派生类时出错
【发布时间】:2019-05-23 23:18:16
【问题描述】:

我正在从 std::exception 派生一个类,但出现错误 这是我的代码

#include "stdafx.h"
#include <iostream>

using namespace std;

class exp1 : public std::exception {
public:
    exp1() noexcept = default;
    ~exp1() = default;
    virtual const char* what() const noexcept
    {
        return "This is an exception";
    }
};


int main()
{
    try{
        int i; 
        cin >> i;
        if(i == 0)throw exp1() ;
        else {cout << i << endl;}
       }
    catch(exp1 & ex){
        cout << ex.what() << endl; 
       }
return 0;
}

我的代码工作正常,但是当我在构造函数中包含 noexcept

exp1() noexcept = default;

然后我得到错误

'exp1::exp1(void) noexcept': attempting to reference a deleted function 

the declared exception specification is incompatible with the generated one 

【问题讨论】:

  • 什么编译器?什么编译器版本?请发帖minimal reproducible example
  • 我用的是VS2015
  • @PaulMcKenzie 我的代码有什么问题?我正在使用 VS2015
  • 适用于 gcc/clang Demo
  • 如果我不得不猜测,我怀疑在 VC2015 实现中std::exception 的默认构造函数没有标记为noexceptexp1 默认构造函数调用它,所以不能是 noexcept 本身。

标签: c++ c++11 exception


【解决方案1】:

您已将exp1 类的构造函数指定为noexceptdefault。这意味着编译器将为您生成一个构造函数。这样做时,它会继承父类的异常规范(如果有的话)。

根据 C++ 标准,std::exception 应该有一个 noexcept 构造函数,如果在您的情况下是这种情况,您就不会出现此编译器错误。但是,Visual Studio 2015 的第一个版本不符合 C++ 标准,这就是您收到此编译器错误的原因。

更高版本的 Visual Studio 2015 符合 C++ 标准,不会再触发编译器错误。我已使用 Visual Studio 14.0.25431.01 Update 3 对此进行了测试,您的代码编译良好。

所以如果你仍然遇到这个问题,那么请升级到更高版本的 Visual Studio 2015。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-16
    • 2011-05-16
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    相关资源
    最近更新 更多