为什么我的工会没有显示正确的价值观? [英] Why does my union not show the correct values?

查看:111
本文介绍了为什么我的工会没有显示正确的价值观?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 <的较低位/ code>。

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 工会,你将有两个一个<$ C $空间C> 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.

这篇关于为什么我的工会没有显示正确的价值观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆