typedef 语法中名称和类型的正确位置是什么?

Tes*_*ser 1 c++ typedef c++17

通常typedef的语法如下

typedef <existing_name> <new_name>
Run Code Online (Sandbox Code Playgroud)

但在下面的例子中,我有点困惑

  typedef char yes[1];
  typedef char no[2];
Run Code Online (Sandbox Code Playgroud)

上面这个似乎有效。为什么以及如何?

难道不应该写成下面这样吗?

  typedef yes char[1];
  typedef no char[2];
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 6

通常 typedef 的语法是...

不,这不准确。通常的语法是

typedef <variable declaration>;
Run Code Online (Sandbox Code Playgroud)

然后声明被分解,变量的名称成为变量本来具有的类型的新名称。您感到困惑的案例与此相符。如果没有typedef,这就是声明数组变量的方式。添加typedef,变量名称将成为该类型的新名称。

当然,现代类型别名实际上看起来更像您所期望的

using yes = char[1];
using no  = char[2];
Run Code Online (Sandbox Code Playgroud)

从某种意义上说,这是好的,因为它不需要人们理解 C++ 的声明符语法,只是为了查看类型的名称是什么。不过,人们仍然需要理解在右侧编写类型的语法......

  • 至少现在我知道为什么要引入“using”了:) (2认同)