C++ 结构和联合

结构与联合体是C语言中就已经存在的数据类型。C++语言对它们进行了扩展,最大的变化是允许在结构和联体中定义成员函数。

 1 #include<iostream>
 2 using namespace std;
 3 struct Room{
 4     int floor;
 5     int No;
 6 };
 7 struct Student{
 8     int age;
 9     int score;
10     Student(int a,int s){
11         age = a;
12         score = s;
13     }
14 };
15 int main(){
16     Room r[3] = {{1,101},{2,201},{3,301}};
17     Student s(18,80);//结构体的构造函数
18     cout<<"The rooms are:";
19     cout<<r[0].floor<<"_"<<r[0].No<<endl;
20     cout<<"The student is"<<s.age<<"_"<<s.score<<endl;
21 }

1、利用结构定义变量时,不需要带上关键字struct
2、允许在struct中定义成员函数。默认访问权限为public
3、在struct中没显定义任何构造函数,那可以用{}进行初始化,如果定义了构造函数,则必须用构造函数的形式初始化。

 

 

联合:多种变量共用一个存储空间,已达到节省空间的作用。

 1 #include<iostream>
 2 using namespace std;
 3 union testunion{
 4     char c;
 5     int i;
 6 };
 7 int main(){
 8     cout<<sizeof(testunion)<<endl;//它由较大的类型(int)决定。
 9     testunion *pt = new testunion;
10     char *p = reinterpret_cast<char *>(pt);//p指向一个数组,大小为4。因为int为4个字节,char为1个字节
11     for(int i=0;i<sizeof(*pt);++i){  //所以循环4次。
12         cout<<int(p[i])<<" ";
13     }
14     cout<<endl;
15     cout<<pt->i<<endl;
16     pt->c = 'A';
17     cout<<pt->c<<endl;
18     for(int i =0;i<sizeof(*pt);++i){
19         cout<<int(p[i])<<" ";
20     }
21     cout<<endl;
22     cout<<pt->i<<endl;
23     delete pt;
24 }

 

View Code

 

转载于:https://www.cnblogs.com/teng-IT/p/6014824.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值