结构体指针和结构体嵌套
结构体指针
创建一个结构体指针
struct Student {
//成员列表
string name;
int age;
int score;
};
//创建一个结构体指针指向结构体变量
Student* stup = &S1;
通过结构体指针访问结构体变量的属性 符号’->’
//通过指针访问结构体变量的属性->
cout << "姓名: " << stup->name << "年龄: " << stup->age << "分数: " << stup->score<< endl;
结构体的嵌套
在一个结构体中嵌套另一个结构体
struct Student {
//成员列表
string name;
int age;
int score;
};
//结构体的嵌套
struct Teacher {
int id;
string name;
int age;
Student stu;//辅导的学生
};
给嵌套的结构体赋值
//创建一个Teacher
Teacher th;
//给th的属性赋值
th.id = 10000;
th.name = "老王";
th.age = 40;
th.stu.name = "多多";
th.stu.age = 5;
th.stu.score = 100;
获取嵌套结构体变量的属性值
cout << "老师姓名:" << th.name << " 老师年龄: " << th.age << " 老师编号: " << th.id <<endl;
cout << "学生姓名: " << th.stu.name << "学生年龄: " << th.stu.age << " 学生分数: " << th.stu.score << endl;