对what()调用的解释

Nuc*_*ore 0 c++ syntax

using namespace std;

struct MyException : public exception
{
  const char * what () const throw () // <--- This
  {
    return "C++ Exception";
  }
};
Run Code Online (Sandbox Code Playgroud)

请考虑标记的行.有人可以解释一下该语句中使用的语法

我想我应该把我的查询缩小到 "const throw()" 部分......

谢谢大家的回复

Mik*_*our 5

它是成员函数定义.

  • const char * 是返回类型,指向常量字符的指针,按惯例,是以零结尾的字符串数组的第一个字符.
  • what 是函数名称
  • () 是一个空参数列表,表示该函数不带参数
  • const限定函数,因此可以在const对象上调用它,而不能直接修改对象的成员
  • throw () 是一个异常规范,可以防止它抛出任何异常.

这将覆盖exception基类中声明的虚函数,允许您获取描述抛出的特定异常的文本消息:

try {
    // Throw a specific type
    throw MyException();
} catch (std::exception const & ex) {
    // Catch a generic type and extract the message
    std::cerr << ex.what() << '\n';  // prints "C++ Exception"
}
Run Code Online (Sandbox Code Playgroud)