如何使派生构造函数将连接值传递给其父构造函数?

时间:2013-12-26 22:20:04

标签: c++ constructor initializer-list

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

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&amp;)。我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分:4)

一个常见的范例是创建辅助函数:

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()