为什么我的工会没有显示正确的价值观?
union
{ int i;
bool b;
} x;
x.i = 20000;
x.b = true;
cout << x.i;
据打印出19969.为什么它没有打印出20000?
It prints out 19969. Why does it not print out 20000?
A 联盟
不是结构
。在一结合
中,所有的数据的占有相同的空间,并可以通过其字段名被视为不同的类型。当您指定真正
到 XB
,要覆盖 20000 。
A union
is not a struct
. In a union
, all of the data occupies the same space and can be treated as different types via its field names. When you assign true
to x.b
, you are overwriting the lower-order bits of 20000
.
更具体地说:
在二进制20000:100111000100000
20000 in binary: 100111000100000
在二进制19969:100111000000001
19969 in binary: 100111000000001
这里发生了什么是你把1(00000001)一个字节的值在20万8较低位。
What happened here was that you put a one-byte value of 1 (00000001) in the 8 lower-order bits of 200000.
如果您使用的结构
而不是 A 工会,你将有两个一个 INT
和布尔
,而不仅仅是一个 INT
,你会看到您预期的结果。
If you use a struct
instead of a union
, you will have space for both an int
and a bool
, rather than just an int
, and you will see the results you expected.