本节内容:结构体
#include <iostream>
using namespace std;
//结构体
//1、创建学生数据类型:学生包括(姓名,年龄,分数)
struct Student
{
//成员列表
//姓名
string name;
//年龄
int age;
//分数
int score;
}s3; //第三种创建成员方法
//2、通过学生类型创建具体学生
/*
三种方式:
1、struct Student s1
2、struct Student s2 = {}
3、在定义结构体时顺便创建结构体变量
*/
//结构体嵌套结构体
/*
作用:结构体中的成员可以是另一个结构体
例如:每个老师辅导一个学员,
一个老师的结构体中,
记录一个学生的结构体
*/
//定义学生结构体
struct student
{
string name; //学生姓名
int age;
int score;
};
//定义老师结构体
struct teacher
{
int id; //教师编号
string name; //教师姓名
int age; //年龄
struct student stu; //辅导的学生
};
//声明函数
void printStudent1(struct Student s);
void printStudent2(struct Student* p);
int main()
{
//1、struct Student s1
//struct 也可以省略
struct Student s1;
s1.name = "张三";
s1.age = 18;
s1.score = 100;
cout << "姓名:" << s1.name << " 年龄:" << s1.age << " 分数:" << s1.score << endl;
//2、struct Student s2 = {}
struct Student s2 = { "李四", 19, 80 };
cout << "姓名:" << s2.name << " 年龄:" << s2.age << " 分数:" << s2.score << endl;
//3、在定义结构体时顺便创建结构体变量
s3.name = "王五";
s3.age = 20;
s3.score = 60;
cout << "姓名:" << s3.name << " 年龄:" << s3.age << " 分数:" << s3.score << endl;
//创建结构体数组
struct Student stuArray[3] =
{
{"张三", 18, 100},
{"李四", 28, 99},
{"王五", 28, 66}
};
//给结构体数组中的元素赋值
stuArray[2].name = "赵六";
stuArray[2].age = 80;
stuArray[2].score = 60;
//遍历结构体数组
for (int i = 0; i < 3; i++)
{
cout << "姓名:" << stuArray[i].name
<< " 年龄:" << stuArray[i].age
<< " 分数:" << stuArray[i].score
<< endl;
}
//通过指针指向结构体变量
struct Student* p = &s1;
//通过指针访问结构体变量中的数据
cout << "姓名:" << p->name
<< " 年龄:" << p->age
<< " 分数:" << p->score
<< endl;
teacher t1;
t1.id = 1000;
t1.name = "老王";
t1.age = 50;
t1.stu.name = "小王";
t1.stu.age = 20;
t1.stu.score = 60;
cout << "老师姓名:" << t1.name << " 老师编号:" << t1.id
<< " 老师的年龄:" << t1.age << endl
<< " 老师辅导的学生姓名:" << t1.stu.name
<< " 学生年龄:" << t1.stu.age
<< " 学生的考试分数:" << t1.stu.score << endl;;
//结构体做函数参数
//值传递
printStudent1(s1);
//地址传递
printStudent2(&s1);
// 结构体中 const使用场景:用来防止误操作
//参数前面加一个const:void printStudent2(const struct Student* p)
system("pause");
return 0;
}
//打印学生信息函数
//值传递
void printStudent1(struct Student s)
{
cout << "子函数中,姓名:" << s.name
<< " 年龄:" << s.age
<< " 分数:" << s.score << endl;
}
//地址传递,这种方式节省内存空间
//值传递会把结构体所有数据拷贝一份,而地址传递只有一个4字节
void printStudent2(struct Student* p)
{
cout << "子函数2中,姓名:" << p->name
<< " 年龄:" << p->age
<< " 分数:" << p->score << endl;
}
//参数前面加一个const:void printStudent2(const struct Student* p)
/*
void printStudent2(const struct Student* p)
{
p->age = 100; //此时这条会报错,因为传入的是常量指针,值不可修改
cout << "子函数2中,姓名:" << p->name
<< " 年龄:" << p->age
<< " 分数:" << p->score << endl;
}
*/
/*
拓展部分:
小案例中比较关键的代码:
用循环来给成员属性初始化
string nameSeed = "ABCDE";
for (int i = 0; i < len; i++)
{
tArray[i].tName = "Teacher_";
tArray[i].tName += nameSeed[i];
}
其实字符串就是字符数组,这段代码用循环拼接的方式给
老师名字初始化:Teacher_A,Teacher_B。。。
*/
一节一篇代码,简单粗暴,适合快速学习/复习C++基础知识。