c++ - 未命名类

标签 c++ class

受到 discussion 的启发

C++类的语法定义为

class-key identifier *[opt]* base-clause *[opt]*(斜体是我的)

这对我来说意味着类名是可选的,我们可以在 C++ 中使用未命名的类。

那么,下面的格式是否正确?

struct X{
   struct{
      int x;
      int y;
   };
};

int main(){}

VS: error C2467: illegal declaration of anonymous 'struct'

Comeau online: error: declaration does not declare anything struct{

GCC(ideone): Compiles fine

有什么想法吗?

最佳答案

不,它的格式不正确。您不能仅从这些语法语句中推导出语言句法。还必须考虑标准文本中给出的额外要求。在这种情况下会是

7 Declarations

...

3 In a simple-declaration, the optional init-declarator-list can be omitted only when declaring a class (clause 9) or enumeration (7.2), that is, when the decl-specifier-seq contains either a class-specifier, an elaboratedtype-specifier with a class-key (9.1), or an enum-specifier. In these cases and whenever a class-specifier or enum-specifier is present in the decl-specifier-seq, the identifiers in these specifiers are among the names being declared by the declaration (as class-names, enum-names, or enumerators, depending on the syntax). In such cases, and except for the declaration of an unnamed bit-field (9.6), the decl-specifier-seq shall introduce one or more names into the program, or shall redeclare a name introduced by a previous declaration.

在这种情况下,最后一句话很重要

“可选”部分仅用于允许像这样的声明

struct { int x; } s;
typedef struct { int x, y; } Point;

第一个声明没有链接的类类型和该类型的变量 s。请注意,没有链接的类型不能用于声明具有链接的变量,这意味着这样的声明不能在命名空间范围内使用。

你的例子格式不正确,但这是合法的

struct X {
   struct {
      int x;
      int y;
   } point;
};

此外,无名类语法用于声明匿名 union (尽管我对 7/3 没有提到匿名 union 这一事实感到有点困惑)。

关于c++ - 未命名类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3607177/

相关文章:

c++ - Qt 在 Linux 上不显示 PNG 图像

c++ - 如何把一个系统环境变量作为一个宏定义到一个C头文件中?

绑定(bind)对象函数时出现 C++ 异步错误

c++ - 模板类遇到 __declspec(import) 时出现 Visual Studio 链接器错误

c# - 静态 ConfigurationManager 访问类操作

c++ - 错误 : No match for 'operator>>' Overloading istream operator

java - 将对象存储在数组中

c++ - 递归静态成员函数 VS 普通成员函数

c++ - 如何在 C++ 中访问成员函数内的对象数组?

c++ - 使用返回类型作为派生类的指针