关于位域如何节省内存(C++)
2015-03-13 10:27
316 查看
位域: 最先使用在c语言中后来C++继承了这一优良的特点。
举个栗子: int --> 4字节 2^32位 ,如果我们只需要其表达一个0~16的数字,
使用一个int就显得稍稍有些许浪费,所以我们这里就可以使用到位域0~16 --> 2^1 ~ 2^5
我们就可以这样来声明了: int sudo: 5; 就可以了!
View Code
举个栗子: int --> 4字节 2^32位 ,如果我们只需要其表达一个0~16的数字,
使用一个int就显得稍稍有些许浪费,所以我们这里就可以使用到位域0~16 --> 2^1 ~ 2^5
我们就可以这样来声明了: int sudo: 5; 就可以了!
/* 设计一个结构体存储学生的成绩信息, 需要包括学号,年纪和成绩3项内容,学号的范围是0~99 999 999, 年纪分为freshman,sophomore,junior,senior四种, 成绩包括A,B,C,D四个等级。 请使用位域来解决: */ #include<iostream> using namespace std; enum Age{ freshman , sophomore , junior ,senior } ; enum grade{ A , B , C , D }; class student { private : unsigned int num :27; Age age : 2 ; grade gra:2 ; public : /* 析构函数 */ ~ student(){ cout<<"student has been xigou l ! "; } /* 构造函数 */ student(unsigned int num , Age age , grade gra ); void show(); } ; student::student(unsigned int num , Age age , grade gra ):num(num),age(age),gra(gra){ }; inline void student::show(){ cout<<"学号为:"<<this->num<<endl; string sag; //采用枚举 switch(age){ case freshman : sag = "freshman" ; break ; case junior : sag = "junior" ; break ; case senior : sag = "senior" ; break ; case sophomore : sag = "sophomore" ; break ; } cout<<"年纪为:"<<sag<<ends; cout<<"成绩为:"<<char('A'+gra)<<endl; } int main(int args [] ,char argv[]){ student stu(12345678,sophomore,C) ; stu.show(); cout<<sizeof stu<<endl; return 0; }
View Code
/* 编写一个名为CPU的类,描述一个CPU的以下信息: 时钟频率,最大不会超过3000MHZ = 3000*10^6 ;字长,可以 是32位或64位;核数,可以是单核,双核,或四核,是否 支持超线程。各项信息要求使用位域来表示。通过输出sizeof (CPU)来观察该类所占的字节数。 */ #include<iostream> #include<string> using namespace std; //字长 enum word{ a, b }; //核数 enum keshu{one ,two ,four }; //是否支持超线程 enum es_no{yes ,no} ; class intel_CPU{ private : // 2^29 = 536 870 912 unsigned int tp : 29 ; word wd : 1 ; keshu ks : 2 ; es_no en : 1 ; public : //构造函数 intel_CPU(int tp=0,word wd=a,keshu ks=two,es_no en=no): tp(tp),wd(wd),ks(ks),en(en){ cout<<"this is a construct !"<<endl; }; //析构函数 ~intel_CPU(); void show(); }; intel_CPU::~intel_CPU(){ cout<<"this is a 析构函数!!"<<endl; } void inline intel_CPU::show() { cout<<"时钟频率为:"<<ends; cout<<tp<<endl; cout<<"字长为【32 or 64】: "; if(wd==a)cout<<32<<endl; else cout<<64<<endl; switch (ks){ case one : cout<<"单核"<<endl; break; case two : cout<<"双核"<<endl; break; case four: cout<< "四核”"<<endl; break; default : cout<<"山寨机,没核" ; break; } cout<<"是否支持超线程模式:"<< (en==yes?"支持":"不支持")<<endl; } int main(){ intel_CPU icp(123456789); icp.show(); cout<<sizeof icp<<endl; }
相关文章推荐
- 如何用C++进行内存分配
- c/c++中指针参数如何传递内存
- 关于如何编写指向内存插放的音频解码器
- 关于C++的类对象,内存分布问题
- 关于pragma pack的用法--------------C++中的内存对齐问题
- 高质量c++(指针参数是如何传递内存的?)
- 讨教:WINCE 开发中,如何让.net程序及时地释放内存,如何可以节省内存?
- 转载 关于C++内存 来源:网侠2007
- c/c++中指针参数如何传递内存
- 关于C++内存的一点解释。
- 应用C++特性提高执行速度及节省内存空间(1)
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- c/c++中指针参数如何传递内存
- 如何用C++进行内存分配
- 关于dom4j、dom如何清理内存中已经加载的xml树