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

C++ 如何使派生构造函数将连接的值传递给其父构造函数?,c++,constructor,initializer-list,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 : publi

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

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() {}
};
我理解这是因为bmd2FileException的构造函数试图调用bmd2Exception,但尚未定义。我真正想做的是让bmd2FileException调用bmd2Exceptionconst 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


顺便说一句,如果你的构造函数是连接字符串的,我就不能肯定它是抛出的。

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

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


顺便说一句,如果你的构造函数是连接字符串,我不太确定它是抛出的。

使用mem初始值设定项列表:bmd2FileException/*parameters*/:bmd2Exception/*连接字符串*/{}或者使用另一个类设计,例如bmd2Exception中的受保护默认构造函数并提供某种setter。使用mem初始值设定项列表:bmd2FileException/*parameters*/:bmd2Exception/*连接字符串*/{}或者使用另一个类设计,例如bmd2Exception中的受保护默认构造函数并提供某种setter.+1。也要纠正不必要的投掷。除非通过its显式启用,否则流不会抛出任何异常。如果抛出std::bad_alloc,您会遇到更大的问题,因为析构函数永远不会被调用。我们只是使用该抛出来明确说明,在合理的情况下,该函数不应该抛出任何东西。+1。也要纠正不必要的投掷。除非通过its显式启用,否则流不会抛出任何异常。如果抛出std::bad_alloc,您会遇到更大的问题,因为析构函数永远不会被调用。我们只是使用这个抛出来明确说明,在合理的情况下,这个函数不应该抛出任何东西。