gpt4 book ai didi

C++ 匿名结构

转载 作者:可可西里 更新时间:2023-11-01 16:39:34 25 4
gpt4 key购买 nike

我使用以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com