问题描述
union u
{
char ch [2];
int i;
};
int main()
{
联合ux = {0,2};
cout << cout <返回0 ;
}
为什么会打印512 ??? [confused]这是什么x = {0,2};到底在干什么?
union u
{
char ch[2];
int i;
};
int main()
{
union u x={0,2};
cout<<x.ch<<"\n\n\n";
cout<<x.i<<endl;
return 0;
}
Why does this print 512???[confused] What is this x={0,2}; exactly doing?
推荐答案
-----------------------<br />| 512 |<br />-----------------------<br />| 00000010 | 00000000 |<br />-----------------------<br />| 2 | 0 |<br />-----------------------
union ux = {0,2};
union u x={0,2};
在这里,编译器使用具有ASCII码0
和ch成员(这使我感到有些吃惊). >.偶然地0对应于字符串终止符,因此ch
最终包含一个空字符串,这解释了
Here the compiler initialise the ch
member (this surpised a bit me) of the union with the characters having ASCII codes 0
and 2
. Incidentally 0 corrensponds to string terminator so ch
eventually contains an empty string, this explains the output of the
cout< < x.ch<"\ n \ n \ n";
cout<<x.ch<<"\n\n\n";
行.
这种初始化也会影响整数(i
)成员,并且由于您使用计算机是一个小的字节序,您会得到0 * 2^0 + 2 * 2 ^ 8 = 512
.
这说明了
line.
Such a initialization affect also the integer (i
) member, and since you computer is a little endian one, you get 0 * 2^0 + 2 * 2 ^ 8 = 512
.
This explains the output of the
cout<< ; x.i<< endl;
cout<<x.i<<endl;
line.
:)
line.
:)
union __ChannelsOn<br /> {<br /> BYTE Mask;<br /> struct {<br /> BYTE On1 : 1;<br /> BYTE On2 : 1;<br /> BYTE On3 : 1;<br /> BYTE On4 : 1;<br /> BYTE OnTOF : 1;<br /> BYTE Unused : 1;<br /> BYTE MasterOn : 1;<br /> BYTE ScanOn : 1;<br /> } Bits;<br /> } ChannelsOn;
我有一些硬件,该硬件具有发送给它的命令以打开和关闭通道.我发送一个由标志位组成的字节.我可以说:
I have some hardware that has a command I send to it to turn channels on and off. I send a byte made up of flag bits. I could say:
__ChannelsOn c;<br />c.Mask = 1 << 3 | 1 << 7;<br />SendChannels (c);
或者我说:
or I say:
__ChannelsOn c;<br />c.Mask = 0;<br />c.Bits.On3 = 1;<br />c.Bits.ScanOn = 1;<br />SendChannels (c);
两者都做同样的事情-但这更易读吗?
它们也是用于制作变体结构,用于与COM/VB通讯.
它等效于:
Both do the same thing - but which is more readable?
They are also used to make the variant structure, used to talk with COM/VB.
It''s equivalent to:
struct VARIANT<br />{<br /> int nType;<br /> union {<br /> int nInt;<br /> long lLong;<br /> DWORD dwDword;<br /> BSTR bstr;<br /> } Var;<br />};
希望对您有所帮助,
伊恩
I hope that helps a bit,
Iain.
这篇关于联盟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!