12.结构体、枚举、联合和别名

  • 结构体的应用
  • 结构体的大小
  • 枚举的定义
  • 联合的定义
  • 类型定义符

结构体的应用

用于在c++中定义新的数据类型

语法:

struct 结构体名{  数据类型 变量名; ........  };

eg:

struct item
{
    int data;
    char word[5];
    float num;
};

int main()
{
    item m = { 1,"小明",0.7 };

    item u = { 2,"小红"};
    cout << m.data << "," << m.num << "," << m.word << endl;
    cout << u.data << "," << u.num << "," << u.word << endl;
}

 

结构体指针

语法:

结构体名* 变量名

struct item
{
    int data;
    char word[5];
    float num;
};

int main()
{
    item m = { 1,"小明",0.7 };

    item u = { 2,"小红"};
    item* n = &u;  // 结构体指针
    cout << m.data << "," << m.num << "," << m.word << endl;
    cout << n->data << "," << n->num << "," << n->word << endl;
}

 

结构体大小

结构体大小取决于,最大变量大小

struct item
{
    int data;
    char word[5];
    float num;
};

int main()
{
    item u = { 2,"abcd"};
    cout << u.data << "," << u.num << "," << u.word << endl;
    cout << sizeof(u) << endl;
}

结构体内变量大小相同时,大小为总和

struct item
{
    int data;
    char word[5];
    float num;
};


struct item2
{
    int data;
    char word;
    float num;
};

int main()
{
    item2 n = { 1,'r',0.6 };
    item u = { 2,"abcd"};
    cout << u.data << "," << u.num << "," << u.word << endl;
    cout << n.data << "," << n.num << "," << n.word << endl;
    cout << sizeof(n) << endl;
    cout << sizeof(u) << endl;
}

 

枚举的定义

语法:

enum 枚举名{枚举值}

eg:

enum Day{MON,TUE,WED,THU,FRI,SAT,SUN};

int main()
{
    Day data = Day(1);

    if (data==TUE)
        cout << "TUE" << endl;
    data = MON;
    cout << data << endl;
    return 0;
}

 

联合的定义

多种数据的组合,但是调用只能使用其中一种

union Data
{
    const char word[11];
    int data;
}x = {"mon"};  // 默认初始化

int main()
{
    cout << x.word << endl;
    Data m = { 1};
    cout << m.data << endl;
    cout << sizeof m;  
    return 0;
}
 输出为:mon
    1

     12

联合的大小取决,最大变量

 

类型定义符

可以为数据类型取别名

语法:

typedef 数据类型 别名

int main()
{
    typedef char Name[25];
    Name people="xiaomin";
    cout << people;
    return 0;
}

输出:小明

返回目录

posted @ 2023-05-31 11:22  微纯册  阅读(55)  评论(0编辑  收藏  举报