位域: 最先使用在c语言中后来C++继承了这一优良的特点。
举个栗子: int --> 4字节 2^32位 ,如果我们只需要其表达一个0~16的数字,
使用一个int就显得稍稍有些许浪费,所以我们这里就可以使用到位域0~16 --> 2^1 ~ 2^5
我们就可以这样来声明了: int sudo: 5; 就可以了!
1 /* 2 设计一个结构体存储学生的成绩信息, 3 需要包括学号,年纪和成绩3项内容,学号的范围是0~99 999 999, 4 年纪分为freshman,sophomore,junior,senior四种, 5 成绩包括A,B,C,D四个等级。 6 请使用位域来解决: 7 */ 8 #include<iostream> 9 10 using namespace std; 11 12 enum Age{ freshman , sophomore , junior ,senior } ; 13 14 enum grade{ A , B , C , D }; 15 16 class student { 17 private : 18 unsigned int num :27; 19 Age age : 2 ; 20 grade gra:2 ; 21 public : 22 /* 析构函数 */ 23 ~ student(){ 24 cout<<"student has been xigou l ! "; 25 } 26 /* 构造函数 */ 27 student(unsigned int num , Age age , grade gra ); 28 void show(); 29 } ; 30 31 student::student(unsigned int num , Age age , grade gra ):num(num),age(age),gra(gra){ 32 }; 33 34 inline void student::show(){ 35 36 cout<<"学号为:"<<this->num<<endl; 37 string sag; 38 //采用枚举 39 switch(age){ 40 case freshman : sag = "freshman" ; break ; 41 case junior : sag = "junior" ; break ; 42 case senior : sag = "senior" ; break ; 43 case sophomore : sag = "sophomore" ; break ; 44 } 45 cout<<"年纪为:"<<sag<<ends; 46 cout<<"成绩为:"<<char('A'+gra)<<endl; 47 } 48 49 int main(int args [] ,char argv[]){ 50 51 student stu(12345678,sophomore,C) ; 52 stu.show(); 53 cout<<sizeof stu<<endl; 54 return 0; 55 }