首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于位域的有关问题,

2012-09-05 
关于位域的问题,求助!#include iostream.hstruct Test{int a:2int b:2int c:1}testint main(int arg

关于位域的问题,求助!
#include "iostream.h"

struct Test 
{
int a:2;
int b:2;
int c:1;
}test;

int main(int argc, char* argv[])
{
test.a = 1;
test.b = 3;
test.c = 1;
cout<<test.a<<endl;
cout<<test.b<<endl;
cout<<test.c<<endl;
  return 0;
}


在VC6.0下结果是1,-1,-1,求解释!!

[解决办法]
你定义的是有符号数,当然结果是这样,比如3 = (11)b,符号位为1,所以结果是-1,这样改即可:

C/C++ code
#include <iostream>using namespace std;struct Test {    unsigned int a : 2;    unsigned int b : 2;    unsigned int c : 1;}test;int main(int argc, char* argv[]){    test.a = 1;    test.b = 3;    test.c = 1;    cout << test.a << endl;    cout << test.b << endl;    cout << test.c << endl;      return 0;} 

热点排行