结构体
2020-04-29 本文已影响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;
}