作用:结构体的的参数成员包含另一个结构体。利用 “.” 操作符来逐级访问结构体中的元素。
1.先来个普通的结构体嵌套,(不涉及数组)。
#include <iostream>
using namespace std;
struct student{
string name; //name不会和下面的name起冲突,因为作用域
int score;
int age;
};
//定义教师结构体,里面包含学生的结构体,一对一的关系。一个特定的老师带着一个特定的学生
struct teacher{
int id;
string name;
int age;
struct student stu;
}; //定义一个teacher对象,并对其进行初始化 (学习这种初始化的格式)
teacher t{
100,//techer.id
"老王八",//teacher.name
35,//teacher.age;
{ "小李",//teacher.stu.name
99,//teacher.stu.score
18,//teacher.stu.age
}
};
int main(){
cout<<t.stu.name<<endl;//通过此来访问教师结构体中的name变量
}
2.上个相对较复杂的(其实也不复杂,搞懂内在逻辑联系就很简单),结构体嵌套+数组。
#include <iostream>
using namespace std;
struct student{
string name; //name不会和下面的name起冲突,因为作用域
int score;
int age;
};
//定义教师结构体,里面包含学生的结构体,一对一的关系。一个特定的老师带着一个特定的学生
struct teacher{
int id;
string name;
int age;
struct student stu;
};
//定义一个教师数组,并对其初始化(学习这种初始化的格式)
teacher obj[2]={
{100,"asdas",1000,{.name="adsdaada",.score=100000,.age=10}},
{100,"asdas",10000,{.name="adsdaada",.score=100000,.age=1012}}
};
int main(){
//这里就可以通过.操作符对数组中的数据进行访问。
cout<<obj[1].stu.age<<endl;
}