我对许多网站感到困惑:那里的人们将class/struct
称为匿名,当它没有名称时,例如:
struct{
int x = 0;
}a;
我认为上面的例子创建了一个未命名的struct
,而不是一个匿名的struct
。我认为匿名struct/class
在结束类体的右花括号之后和结束类定义的分号之前没有名称也没有声明符:
class { // Anonymous class
int x_ = 0;
}; // no delcarator here
当然,标准拒绝上面这样的声明,因为它是病态的。
union
s可以是Unnamed或Anonymous:union{ char unsigned red_; char unsigned green_; char unsigned blue_; long unsigned color_ = 255; } color;
在上面的例子中,我声明了一个未命名的(但不是匿名的)联合,这与上面的类/结构类似。
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
,代码工作得很好。原因是编译器将自动合成该匿名联合的对象,并且我们可以直接访问其成员。(尽管有一些限制)。我认为编译器不允许匿名类/结构,因为它不会自动创建该类型的对象。
那么我的想法是正确的吗?如果不是,请引导我。谢谢你!
在c++标准(N4659)的术语中,只有联合可以是"匿名的"。无论是"匿名类"还是"匿名类"非匿名结构;出现在标准中的任何地方。事实上,"匿名"这个词它在标准中只出现了44次:42次跟在"union"后面,两次单独出现在"union"下面。索引子列表