【问题标题】:C++ anonymous structsC++ 匿名结构
【发布时间】:2013-04-18 15:05:45
【问题描述】:

我使用以下联合来简化字节、半字节和位操作:

union Byte
{
  struct {
    unsigned int bit_0: 1;
    unsigned int bit_1: 1;
    unsigned int bit_2: 1;
    unsigned int bit_3: 1;
    unsigned int bit_4: 1;
    unsigned int bit_5: 1;
    unsigned int bit_6: 1;
    unsigned int bit_7: 1;
  };

  struct {
    unsigned int nibble_0: 4;
    unsigned int nibble_1: 4;
  };

  unsigned char byte;
};

效果很好,但也会产生以下警告:

警告:ISO C++ 禁止匿名结构 [-pedantic]

好的,很高兴知道。但是......如何从我的 g++ 输出中得到这个警告?有没有可能写出类似这个联合的东西而没有这个问题?

【问题讨论】:

  • 为什么不简单地命名你的结构?
  • 在有效的 C++ 领域内,您将无法做您想做的事情。它可能会起作用,但它会是未定义的行为。
  • 我可以命名它 - 例如 struct nibbles 并使其成为联合的字段。但随后我将不得不访问它 Byte.nibbles.nibble_0。使用起来不会那么好;)。
  • 或者,Byte.nibble.n0Byte.nibble._<0>()Byte.nibble._[0]get<0>(Byte.nibble) 或者因为您可以在访问时将重复的 nibble 干燥并丢弃在名为 nibblestruct 中,或许还可以穿上一些商业服装来修饰它。
  • @KerrekSB 所说的。例如,Gcc 将使用字节顺序反转字段顺序,使第 7 位显示为第 0 位。您最好使用bool bit(unsigned int n) const { return byte & (1 << n); }

标签: c++ struct unions anonymous-struct


【解决方案1】:

gcc 编译器选项-fms-extensions 将允许非标准匿名结构没有警告。

(该选项启用它认为的“Microsoft 扩展”

你也可以在valid C++中使用这个约定来达到同样的效果。

union Byte
{
  struct bits_type {
    unsigned int _0: 1;
    unsigned int _1: 1;
    unsigned int _2: 1;
    unsigned int _3: 1;
    unsigned int _4: 1;
    unsigned int _5: 1;
    unsigned int _6: 1;
    unsigned int _7: 1;
  } bit;
  struct nibbles_type {
    unsigned int _0: 4;
    unsigned int _1: 4;
  } nibble;
  unsigned char byte;
};

有了这个,你的非标准byte.nibble_0变成了合法的byte.nibble._0

【讨论】:

  • 您对前导下划线是正确的。全局命名空间中以下划线开头的名称保留给实现。以下划线后跟大写字母或包含双下划线的名称也保留给实现。 - 见 17.6.4.3.2 (C++11)
猜你喜欢
  • 2020-10-28
  • 2016-03-30
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多