自定义异常类的C ++语法

时间:2013-07-16 15:52:24

标签: c++ exception custom-exceptions

我是C ++的新手,并且发现了以下代码片段,用于从std :: exception扩展的自定义异常。我不理解的唯一部分是构造函数定义之后的: err_msg(msg) {}。谁能解释为什么这不在函数括号中?

class my_exception : public std::exception {
  private:
    std::string err_msg;

  public:
    my_exception(const char *msg) : err_msg(msg) {};
    ~my_exception() throw() {};
    const char *what() const throw() { return this->err_msg.c_str(); };
};

1 个答案:

答案 0 :(得分:4)

成员err_msg已由初始化列表初始化。

my_exception(const char *msg) : err_msg(msg) {};
//                         here ^^^^^^^^^^^^

所以对于构造函数无关。


编辑:

关于在异常中不使用std :: string的讨论很多。只需google for it或查看here