2017-06-02 81 views
0

我想從stdexcept的邏輯錯誤中創建自己的錯誤。我嘗試了以下內容,並面臨錯誤,我的猜測是,它不是正確的做法。我無法在google或以前的堆棧溢出問題上找到答案,請原諒我的低調。如何在C++中創建logic_error的自定義派生類?

// 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 

回答

1

您必須在類的構造函數的初始化程序列表中調用基類的構造函數。
像這樣:

My_custom_exception::My_custom_exception(string message): 
    logic_error(message) 
{ 
} 
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; 
}; 
相關問題