无法理解此 C++ 表达式的 syntax/structure

Can't understand the syntax/structure of this C++ expression

请让我澄清一下,我在解释问题时可能使用了不正确的术语。请耐心等待 - 请指出缺陷,但我希望我的问题的本质在字里行间得到了传达。

#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception { 
   const char * what () const throw () {
      return "C++ Exception";
   }
};

int main() {
   try {
      throw MyException();
   } catch(MyException& e) {
      std::cout << "MyException caught" << std::endl;
      std::cout << e.what() << std::endl;
   } catch(std::exception& e) {
      //Other errors
   }
}

我正在尝试学习 C++,之前学过 C。

在上面的代码中,我不明白特定行的语法:

const char * what () const throw ()

我从 那里读到的是

  1. const char * 是 return 类型,指向常量字符的指针,按照惯例,它是零终止字符串数组的第一个字符。

  2. what是函数名

  3. ()为空参数列表,表示函数不带参数

  4. const限定了函数,所以可以在const对象上调用,不能直接修改对象的成员

  5. throw () 是一个异常规范,可以防止它抛出任何异常。

但是我不明白的是:

在 C 中引用函数时,我们将它们定义为

return_type function_ name
  {function_body;
  } 

因此,虽然我知道 const char * 是这里的 return 类型;因此 what 必须是 function_name;我不明白函数体是什么部分。

我最近才知道 C++ 中的 throw 函数;但是为什么what后面有一个'()'呢?如果 throw() 是一个函数,那么它的 return 类型是什么?我们是在这里定义 throw() 还是在这里定义 what()

这是一个已弃用的动态禁止抛出说明符。参见 here。 它不是额外的函数调用。它指定了这个函数的行为方式,在这种情况下,它是否抛出异常,在这种特殊情况下它不会。

While referring to functions in C, we define them as

return_type function_ name
    {function_body;
    } 

C++也是如此。只是在 function_name{function_body} 之间也可以有额外的可选说明符。

And so while I understand const char * is the return-type here; and therefore what must be function_name;

是的。

I don't understand what part is the function body.

正是您所期望的 - 大括号之间的部分:

{ return "C++ Exception"; }

I am newly aware of the throw function in C++;

这不是函数。

but why is there a '()' after what?

您已在问题中说明的原因:"an empty parameter list, indicating that the function takes no arguments"。

And if throw() is a function

不是。它符合 what() 合同规定不抛出任何异常。函数的 throw 说明符的括号说明函数可能抛出的实际异常类型,如果允许 none,则它可能为空。

Are we defining throw() here or what() here?

what()