我对许多网站感到困惑:那里的人们将没有名称的类/结构
称为匿名:例如:
struct{
int x = 0;
}a;
我认为上面的示例创建了一个未命名的struct
,但不是匿名struct
。我认为匿名 struct/class
在结束类主体的大括号之后和结束类定义的分号之前没有名称或声明符:
class { // Anonymous class
int x_ = 0;
}; // no delcarator here
当然,该标准拒绝上述声明,因为它的格式不正确。
union
可以是未命名的或匿名的:union{ char unsigned red_; char unsigned green_; char unsigned blue_; long unsigned color_ = 255; } color;
在上面的示例中,我声明了一个未命名(但不是匿名) union ,这与上面的类/结构类似。
union
可以是匿名的:// cannot be declared in a namespace except adding `static` before the keyword `union` which makes the linkage of the unnamed object local to this TU /*static*/ union{ // Anonymous union char unsigned red_; char unsigned green_; char unsigned blue_; long unsigned color_ = 255; ; }; // no declarator green_ = 247; // ok accessing the member data green_ of the Anonymous union
上面我已经声明了一个匿名
union
并且代码运行得很好。原因是编译器会自动合成该匿名 union 的对象,我们可以直接访问其成员。 (尽管有一些限制)。我认为编译器不允许匿名类/结构,因为它不会自动创建该类型的对象。
那么我的想法正确吗?如果没有请指导我。谢谢!
最佳答案
在 C++ 标准 ( N4659 ) 的术语中,只有 union 可以是“匿名的”。短语“匿名类”和“匿名结构”都没有出现在标准中的任何地方。事实上,“anonymous”一词本身在标准中只出现了 44 次:其中 42 次出现在“union”一词之后,在索引的“union”子列表下单独出现了两次。
关于c++ - C++ 中真的有匿名类/结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68779028/