派生异常不会继承构造函数

Art*_*wan 5 c++ oop inheritance constructor exception

我的代码有问题.

#include <iostream>
#include <stdexcept>

class MyException : public std::logic_error {
};

void myFunction1() throw (MyException) {
    throw MyException("fatal error");
};

void myFunction2() throw (std::logic_error) {
    throw std::logic_error("fatal error");
};

int main() {
    try {
        myFunction1();
        //myFunction2();
    }catch (std::exception &e) {
        std::cout << "Error.\n"
            << "Type: " << typeid(e).name() << "\n"
            << "Message: " << e.what() << std::endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

throw MyException("fatal error");线不起作用.Microsoft Visual Studio 2012说:

error C2440: '<function-style-cast>' : cannot convert from 'const char [12]' to 'MyException'
Run Code Online (Sandbox Code Playgroud)

MinGW的反应非常相似.

这意味着,构造函数std::logic_error(const string &what)未从父类复制到子级中.为什么?

感谢您的回答.

And*_*owl 8

继承构造函数是一个C++ 11特性,它在C++ 03中没有(你似乎正在使用它,我可以从动态异常规范中看出).

但是,即使在C++ 11中,您也需要一个using声明来继承基类的构造函数:

class MyException : public std::logic_error {
public:
    using std::logic_error::logic_error;
};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您只需要明确地编写一个构造函数,该构造函数接受一个std::string或一个const char*并将其转发给基类的构造函数:

class MyException : public std::logic_error {
public:
    MyException(std::string const& msg) : std::logic_error(msg) { }
};
Run Code Online (Sandbox Code Playgroud)