【问题标题】:C++ syntax for custom exception class [duplicate]自定义异常类的 C++ 语法 [重复]
【发布时间】:2013-07-16 15:52:24
【问题描述】:

我对 C++ 相当陌生,并且发现以下代码 sn-p 用于从 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(); };
};

【问题讨论】:

    标签: c++ exception custom-exceptions


    【解决方案1】:

    成员err_msg已经被初始化列表初始化了。

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

    所以对于承包商来说没什么可做的。


    旁注:有一些关于在异常中不使用std::string的讨论。只需谷歌或查看here

    【讨论】:

      猜你喜欢
      • 2012-11-25
      • 2021-08-24
      • 2010-12-25
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      • 2019-02-28
      • 2013-11-01
      相关资源
      最近更新 更多