【发布时间】:2021-08-13 22:44:41
【问题描述】:
我对许多网站感到困惑:那里的人将class/struct 称为匿名,例如,当它没有名称时:
struct{
int x = 0;
}a;
我认为上面的示例创建了一个未命名的struct,但不是一个匿名的struct。我认为 Anonymous struct/class 在结束类主体的大括号之后和结束类定义的分号之前没有名称或声明符:
class { // Anonymous class
int x_ = 0;
}; // no delcarator here
当然,标准拒绝上述这样的声明,因为它格式不正确。
-
unions 可以是未命名的或匿名的: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并且代码工作得很好。原因是编译器会自动合成一个匿名联合的对象,我们可以直接访问它的成员。 (虽然有一些限制)。 -
我认为编译器不允许匿名类/结构,因为它不会自动创建该类型的对象。
所以我的想法正确吗?如果没有,请指导我。谢谢!
【问题讨论】:
-
假设您可以创建类型而不给它一个名称或立即声明实例。您希望代码是什么样子,使用它?
-
@Ext3h:不!匿名联合是 C++ 标准的一部分:请从 cppreference 中查看此内容:en.cppreference.com/w/cpp/language/union 关于匿名联合的部分。
-
我认为术语“未命名结构”和“匿名结构”是同义词,至少在随意使用时是这样。如果您想要标准中的章节,您可能需要考虑
language-lawyer标签。 -
未命名或匿名结构的缺点是您无法提供构造函数或析构函数。 (注意,您可以使用
decltype(a) b; b.x = 5;。)我使用了一个未命名或匿名的结构来在C++ 中实现一个kluge / janky 类型的properties 字段。他们不必因为任何特殊原因而被匿名,我只是不需要给他们命名,所以我没有。