如何在c ++中创建自定义派生类的logic_error?

时间:2017-06-02 06:43:29

标签: c++ c++11 stl

我想从stdexcept创建自己的逻辑错误错误。我尝试了以下内容并面临错误,我的猜测是,这不是正确的做法。我无法在谷歌或之前的堆栈溢出问题上找到答案,请原谅我的新闻。

// Header
class My_custom_exception : public logic_error
{
public:
    My_custom_exception(string message);
}
// Implementation
My_custom_exception::My_custom_exception(string message)
{
    logic_error(message);
}

我不知道如何执行。它给了我以下错误:

exception.cpp: In constructor ‘My_custom_exception::My_custom_exception(std::__cxx11::string)’:
exception.cpp:3:56: error: no matching function for call to ‘std::logic_error::logic_error()’
 My_custom_exception::My_custom_exception(string message)
                                                        ^
In file included from /usr/include/c++/5/bits/ios_base.h:44:0,
                 from /usr/include/c++/5/ios:42,
                 from /usr/include/c++/5/ostream:38,
                 from /usr/include/c++/5/iostream:39,
                 from main.cpp:1:
/usr/include/c++/5/stdexcept:128:5: note: candidate: std::logic_error::logic_error(const std::logic_error&)
     logic_error(const logic_error&) _GLIBCXX_USE_NOEXCEPT;
     ^
/usr/include/c++/5/stdexcept:128:5: note:   candidate expects 1 argument, 0 provided
/usr/include/c++/5/stdexcept:120:5: note: candidate: std::logic_error::logic_error(const string&)
     logic_error(const string& __arg);
     ^
/usr/include/c++/5/stdexcept:120:5: note:   candidate expects 1 argument, 0 provided
In file included from main.cpp:2:0:
exception.cpp:5:21: error: declaration of ‘std::logic_error message’ shadows a parameter
  logic_error(message);
                     ^
exception.cpp:5:21: error: no matching function for call to ‘std::logic_error::logic_error()’
In file included from /usr/include/c++/5/bits/ios_base.h:44:0,
                 from /usr/include/c++/5/ios:42,
                 from /usr/include/c++/5/ostream:38,
                 from /usr/include/c++/5/iostream:39,
                 from main.cpp:1:
/usr/include/c++/5/stdexcept:128:5: note: candidate: std::logic_error::logic_error(const std::logic_error&)
     logic_error(const logic_error&) _GLIBCXX_USE_NOEXCEPT;
     ^
/usr/include/c++/5/stdexcept:128:5: note:   candidate expects 1 argument, 0 provided
/usr/include/c++/5/stdexcept:120:5: note: candidate: std::logic_error::logic_error(const string&)
     logic_error(const string& __arg);
     ^
/usr/include/c++/5/stdexcept:120:5: note:   candidate expects 1 argument, 0 provided

2 个答案:

答案 0 :(得分:1)

您必须在类的构造函数的初始化列表中调用基类的构造函数 像这样:

Username | Firstname | Lastname | email | #actions |

答案 1 :(得分:1)

在构造函数的初始化列表中使用基类构造函数:

My_custom_exception::My_custom_exception(string message)
    : logic_error(message){};

或者从基类继承构造函数(自C ++ 11起):

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