• 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
  • 相关阅读:
    EasyUI改变Layout的Region的宽高,位置等信息
    Linq-C#左连接
    [SQL Server]如何快速查找使用了某个字段的所有存储过程
    NET联调
    Linq-Order By操作
    Java之Filter --Servlet技术中最实用的技术
    JavaWeb之JSON
    JavaSE(一)之认识java
    JavaWeb之Ajax
    【iScroll源码学习02】分解iScroll三个核心事件点
  • 原文地址:https://www.cnblogs.com/teng-IT/p/6014824.html
Copyright © 2020-2023  润新知