C++ 匿名结构

标签 c++ struct unions anonymous-struct

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

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;
};

它运行良好,但它也会生成此警告:

warning: ISO C++ prohibits anonymous structs [-pedantic]

好的,很高兴知道。但是......如何从我的 g++ 输出中得到这个警告?有没有可能在没有这个问题的情况下写出像这个 union 这样的东西?

最佳答案

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

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

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

关于C++ 匿名结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16202576/

相关文章:

C++ : 3 questions about initialization syntax, 值初始化和默认初始化

c++ - 如何在wxwidgets中拖动窗口大小?

c - 结构变量不会因赋值而改变

c++ - uint12 结构中的字节顺序

c++ - ifstream 相当于 FILE * 的倒带方法

c++ - YARN下的C/C++程序

c++ - 'this' 用于结构?

sql - 对 STRUCT 数据类型使用 Like 运算符

c - 在函数参数中使用 union

Swift 中的 C union 类型?