从std :: exception派生类时出现错误

时间:2018-12-25 04:52:49

标签: c++ c++11 exception

enter image description here我从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 

1 个答案:

答案 0 :(得分:0)

您已将类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。

相关问题