如何使派生构造函数将串联值传递给其父构造函数

How can I make a derived constructor pass a concatenated value to its parent constructor?

本文关键字:构造函数 值传 何使 派生      更新时间:2023-10-16

我有两个异常类,一个继承自另一个:

class bmd2Exception : public std::runtime_error
{
  public:
    bmd2Exception(const std::string & _description) throw () : std::runtime_error(_description) {}
    ~bmd2Exception() throw() {}
};
class bmd2FileException : public bmd2Exception
{
  public:
    bmd2FileException(const std::string & _description, const char * _file, long int _line) throw()
    {
      std::stringstream ss;
      ss << "ERROR in " << _file << " at line " << _line << ": " << _description;
      bmd2Exception(ss.str());
    }
    ~bmd2FileException() throw() {}
};

我收到的错误消息:

no matching function for call to ‘bmd2::bmd2Exception::bmd2Exception()’

我知道这是因为 bmd2FileException 的构造函数正在尝试调用尚未定义的 bmd2Exception()。 我真正想发生的是让 bmd2FileException() 调用 bmd2Exception(const std::string &) 并带有连接的错误消息。 我该怎么做?

谢谢!

一种常见的范例是创建一个帮助程序函数:

class bmd2FileException : public bmd2Exception
{
    private:
        static std::string make_msg(const std::string & _description, const char * _file, long int _line);
    public:
        bmd2FileException(const std::string & _description, const char * _file, long int _line)
            : bmd2Exception(make_msg(_description, _file, _line))
        { }      
};

现在只需将您的消息创建代码放在 bmd2FileException::make_msg(...) 中。

顺便说一句,如果您的构造函数正在连接字符串,我不太确定它是throw().