【发布时间】: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.n0或Byte.nibble._<0>()或Byte.nibble._[0]或get<0>(Byte.nibble)或者因为您可以在访问时将重复的nibble干燥并丢弃在名为nibble的struct中,或许还可以穿上一些商业服装来修饰它。 -
@KerrekSB 所说的。例如,Gcc 将使用字节顺序反转字段顺序,使第 7 位显示为第 0 位。您最好使用
bool bit(unsigned int n) const { return byte & (1 << n); }
标签: c++ struct unions anonymous-struct