【问题标题】:Is there really an Anonymous class/struct in C++?C++ 中真的有匿名类/结构吗?
【发布时间】: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 字段。他们不必因为任何特殊原因而被匿名,我只是不需要给他们命名,所以我没有。

标签: c++ anonymous


【解决方案1】:

在 C++ 标准 (N4659) 的术语中,只有联合可以是“匿名的”。标准中的任何地方都没有出现“匿名类”和“匿名结构”这句话。事实上,“匿名”这个词本身在标准中只出现了 44 次:42 次后跟“联合”这个词,在索引的“联合”子列表下面单独出现了两次。

【讨论】:

    猜你喜欢
    • 2018-02-01
    • 2019-09-28
    • 2013-04-18
    • 2020-10-28
    • 2016-03-30
    • 2013-05-19
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多