我的以下代码有问题。

#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;
}
throw MyException("fatal error");行不起作用。 Microsoft Visual Studio 2012这样说:
error C2440: '<function-style-cast>' : cannot convert from 'const char [12]' to 'MyException'

MinGW的反应非常相似。

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

感谢您的回答。

最佳答案

继承构造函数是C++ 11的一项功能,它在C++ 03中不可用(您似乎正在使用,正如我从动态异常规范中所知道的那样)。

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

class MyException : public std::logic_error {
public:
    using std::logic_error::logic_error;
};

在这种情况下,您只需要显式地编写一个接受std::stringconst char*的构造函数,并将其转发给基类的构造函数:
class MyException : public std::logic_error {
public:
    MyException(std::string const& msg) : std::logic_error(msg) { }
};

07-24 09:46
查看更多