C ++匿名结构

时间:2013-04-24 21:30:46

标签: c++ struct unions anonymous-struct

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

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 ++输出中得到这个警告?如果没有这个问题,是否有可能写出这样的联合?

1 个答案:

答案 0 :(得分:6)

gcc编译器选项-fms-extensions将允许非标准的匿名结构,而不会发出警告。

(这使它认为是“微软扩展”)

使用此约定,您也可以在有效的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

相关问题