结构体

作者: 温柔倾怀 | 来源:发表于2020-04-29 14:52 被阅读0次

基本概念

结构体:属于用户自定义的数据类型,允许用户存储不同的数据类型。

定义和使用

typedef struct Student {
    string name;
    int age;
    int score;
}Student;

Student S1 = { "xiaohong",18,33 };

//C++中 创建结构体变量的时候 struct关键字 可以省略
struct Student {
    string name;
    int age;
    int score;
};
Student S1 = { "xiaohong",18,33 };

结构体数组

Student stuArr[3] = {
        {"jinghou",18,22},
        {"nihao",19,33},
        {"wenrou",21,22}
    };

结构体指针

Student s1 = { "wenrou",18,22 };
Student *pstu = &s1;

pstu->name = "nihao";
cout << pstu->name << endl;

结构体中 const 使用

//将函数中的形参改为指针,可以减少内存空间,而且不会复制新的副本出来
void printStu(const Student *s) {   //加const关键字 防止在函数中修改变量
    //s->age = 111; 
    cout << s->age << endl;
}

Student s1 = { "wenrou",18,22 };
printStu(&s1);

结构体案例1

#include <iostream>
#include <cstdlib>
#include <string>
#include <ctime>
using namespace std;

struct Student {
    string name;
    int score;
};

struct Teacher
{
    string tName;
    Student stuArray[5];
};

void allocateSpace(Teacher tArray[], int len)
{
    string nameSeed = "ABCDE";
    for (int i = 0; i < len; i++)
    {
        tArray[i].tName = "Teacher_";
        tArray[i].tName += nameSeed[i]; //注意这里赋值

        for (int j = 0; j < 5; j++)
        {
            tArray[i].stuArray[j].name = "Student_";
            tArray[i].stuArray[j].name += nameSeed[j];
            int randScore = rand() % 61 + 40;   //随机40-100;
            tArray[i].stuArray[j].score = randScore;
        }
    }
}

void printInfo(Teacher tArray[], int len) {
    for (int i = 0; i < len; i++)
    {
        cout << "老师姓名:" << tArray[i].tName << endl;
        for (int j = 0; j < 5; j++)
        {
            cout << "学生姓名:" << tArray[i].stuArray[j].name <<"   ";
            cout << "学生分数:" << tArray[i].stuArray[j].score << endl;

        }
        cout << endl;
    }
}

int main() {
    srand((unsigned int)time(NULL));//设置随机数种子
    
    Teacher tArray[3];
    
    int len = sizeof(tArray) / sizeof(Teacher);
    
    allocateSpace(tArray, len);
    printInfo(tArray, len);
    system("pause");
    return 0;
}

相关文章

  • 结构体

    [toc] 结构体的定义方式 先定义结构体类型,再定义结构体变量 定义结构体类型的同时定义结构体变量 定义结构体类...

  • 【C语言笔记】<十九>结构体

    结构体的基本概念 结构体初始化 结构体的内存存储细节 结构体定义的方式 结构体类型的作用域 指向结构体的指针 结构...

  • C结构体和链表

    一,结构体变量定义及初始化 二,无名结构体 备注:无名结构体很少使用 三,宏定义结构体 四,结构体嵌套 五,结构体...

  • 结构体

    结构体定义* 结构体中的格式:* struch 结构体名* {* 结构体成员变量* }* 结构体中的特点* 1.结...

  • 结构体数组的定义

    结构体数组的定义 1、先定义结构体类型,再定义结构体数组 2、定义结构体类型的同时定义结构体数组 3、省略结构体类...

  • C#结构体,析构方法,跨程序访问

    结构体 结构体定义 结构体的语法格式: struct + 结构体名 { 结构体成员变量(相当于类中的字段) } 结...

  • 结构体

    结构体有名定义 无名定义 结构体嵌套定义 结构体内存对齐 结构体成员初始化 结构体变量引用 结构体的有名定义:直白...

  • 菜鸡学Swift3.0 13.结构体

    结构体 struct 是值类型 1.定义结构体 struct 结构体类型 { var 结构体属性:类型 ...} ...

  • 结构体

    结构体初识 结构体指针 结构体的匿名字段 结构体嵌套 Go语言中的OOP

  • C语言 第九章 结构体

    [TOC] 第九章结构体 结构体的定义 结构体定义2 指针表示结构体

网友评论

      本文标题:结构体

      本文链接:https://www.haomeiwen.com/subject/roogwhtx.html