20.C++结构体嵌套结构体

结构体嵌套结构体

作用:结构体中的成员可以是另一个结构体
例如:每个老师辅导一名学员,一个老师的结构体中,记录一个学生的结构体

#include <iostream>
#include <string>
using namespace std;
//创建一个学生的结构体
struct student
{
    string name;
    int age;
    int score;
};
//定义老师的结构体,嵌套学生的结构体
struct teacher
{
    int id;
    string name;
    int age;
    struct student stu;//使用结构体嵌套时,应先定义嵌套内的结构体
};

int main()
{
    teacher tea;
    tea.id = 0001;
    tea.name = "justin";
    tea.age = 18;
    tea.stu.name = "二逼";
    tea.stu.age = 12;
    tea.stu.score = 90;

    cout << "老师姓名:" << tea.name
         << "老师编号:" << tea.id
         << "老师年龄:" << tea.age << endl
         << "老师辅导学生的姓名:" << tea.stu.name
         << "学生年龄:" << tea.stu.age
         << "学生成绩:" << tea.stu.score << endl;

    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。