【问题标题】:Derived exception does not inherit constructors派生异常不继承构造函数
【发布时间】:2013-04-05 22:12:54
【问题描述】:

下面的代码有问题。

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

感谢您的回答。

【问题讨论】:

    标签: c++ oop exception inheritance constructor


    【解决方案1】:

    继承构造函数是 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) { }
    };
    

    【讨论】:

    • 我在另一个项目中使用 C++11,第一次遇到这个问题。我该怎么做using 部分?无论如何,您的解决方案非常有效。谢谢
    • @ArturIwan:抱歉回答晚了,不得不离开一段时间。我更新了答案以显示语法。但是,我认为VC11不支持继承构造函数。
    • 我已经测试了你的“使用”解决方案,正如你所说,Visual Studio 还不支持它。
    • @ArturIwan:是的,遗憾的是 VC11 远未完全兼容 C++11。
    • 我发现使用 c++11 时遇到 sheisse 的速度之快令人惊讶,即使是在 4 年后。 VC12 也不支持继承构造函数。只有 CTP 可以。 c.f.:blogs.msdn.com/b/vcblog/archive/2013/12/02/…。对我们来说幸运的是 VC14(是的,他们跳过了 13 个)将在 2 周内发布。
    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 2020-07-02
    • 2011-11-13
    • 2015-11-03
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多