c++异常错误

C++ Exceptions error

本文关键字:错误 异常 c++      更新时间:2023-10-16

我已经定义了我自己的异常,我在编译时得到错误:

/home/me/my_proj/CMyExceptions.hpp:38:63: error: no matching function for call to ‘MyException1::MyException1()’
   MyException2(const std::string& msg) : m_msg(msg) {}
                                                   ^
/home/me/my_proj/CMyExceptions.hpp:38:63: note: candidates are:
/home/me/my_proj/CMyExceptions.hpp:23:3: note: MyException1::MyException1(const string&)
   MyException1(const std::string& msg) : m_msg(msg) {}
   ^
/home/me/my_proj/CMyExceptions.hpp:23:3: note:   candidate expects 1 argument, 0 provided
/home/me/my_proj/CMyExceptions.hpp:17:7: note: MyException1::MyException1(const MyException1&)
 class MyException1 : public std::exception
       ^

我的例外是:

class MyException1 : public std::exception
{
private:
  std::string m_msg;
public:
  MyException1(const std::string& msg) : m_msg(msg) {}
  virtual ~MyException1() throw() {};
  virtual const char* what() const throw()
  {
    return m_msg.c_str();
  }
};
class MyException2 : public MyException1
{
private:
  std::string m_msg;
public:
  MyException2(const std::string& msg) : m_msg(msg) {}
  virtual ~MyException2() throw() {};
  virtual const char* what() const throw()
  {
    return m_msg.c_str();
  }
};

我做错了什么?我应该在初始化之前调用父构造函数(MyException1)吗?

您在MyException1中有m_msg并将其再次放在MyException2中。这意味着MyException2实际上包含两个m_msg变量。这是你想要的吗?

错误消息是因为MyException1没有默认构造函数,所以MyException2必须在初始化列表中调用它的构造函数。我建议

class MyException2 : public MyException1
{
public:
    MyException2(const std::string& msg) : MyException1(msg) {}
};