gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:47:33 27 4
gpt4 key购买 nike

我想根据 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

最佳答案

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

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

关于c++ - 如何在 C++ 中创建自定义的 logic_error 派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44322444/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com