在下面的代碼位域操作
#include <iostream>
using namespace std;
struct field
{
unsigned first : 5;
unsigned second : 9;
};
int main()
{
union
{
field word;
int i;
};
i = 0;
cout<<"First is : "<<word.first<<" Second is : "<<word.second<<" I is "<<i<<"\n";
word.first = 2;
cout<<"First is : "<<word.first<<" Second is : "<<word.second<<" I is "<<i<<"\n";
return 0;
}
當我初始化word.first = 2,如預期它更新字的5比特,並給出了期望的輸出。這是'我'的輸出有點混亂。當word.first = 2時,我給出的輸出爲2,當我做word.second = 2時,對於i的輸出是64.因爲它們共享相同的存儲器塊,所以在後一種情況下輸出(對於i) 2?
我的意思是一個字和「I」共享內存塊 –
是的,但是'word.first'和'word.second'字使用不同的位。 –
@oli我正在尋找的解釋。萬分感謝! –