5

我对下面的代码有疑问。

#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)没有从父类复制到子类中。为什么?

感谢您的回答。

4

1 回答 1

8

Inheriting constructors is a C++11 feature which is not available in C++03 (which you seem to be using, as I can tell from the dynamic exception specifications).

However, even in C++11 you would need a using declaration to inherit a base class's constructor:

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

In this case, you just have to write explicitly a constructor that takes an std::string or a const char* and forwards it to the base class's constructor:

class MyException : public std::logic_error {
public:
    MyException(std::string const& msg) : std::logic_error(msg) { }
};
于 2013-04-13T11:39:31.793 回答