您的位置:首页 > 编程语言 > C语言/C++

关于位域如何节省内存(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; 就可以了!

/*
设计一个结构体存储学生的成绩信息,
需要包括学号,年纪和成绩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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: