结构体是什么?
struct是自定义数据类型,是一些类型集合组成的一个类型。
结构体的定义方式
#include<iostream>
using namespace std;
struct Student
{
	string name;
	int age;
	int score;
};
创建结构体变量并赋值
方式一,先创建结构体变量,再赋值
// 创建结构体变量 , 此时可以省略struce关键字
struct Student s1;
// 给结构体变量赋值
s1.name = "zhangsan";
s1.age = 26;
s1.score = 100;
方式二,创建结构体变量的同时赋值
struct Student s2={"zhangsan",26,100};
方式三,创建结构体的时候顺便创建结构体变量
struct Student
{
	string name;
	int age;
	int score;
}s3;
s3.name = "zhangsan";
s3.age = 26;
s3.score = 80;
结构体数组的定义和访问
#include<iostream>
#include<string>
using namespace std;
struct Student
{
    string name;
    int age;
    int score;
};
int main()
{
    struct Student stu_arr[3] = 
    {
        {"张三",18,80},
        {"李四",19,60},
        {"王五",38,66}
    };
    // 给结构体的元素赋值
    stu_arr[2].name = "赵六";
    stu_arr[2].age = 20;
    stu_arr[2].score = 98;
    // 遍历结构体数组
    for(int i=0;i<3;i++)
    {
        cout<<"姓名:"<<stu_arr[i].name<<"年龄: "<<stu_arr[i].age<<"分数: "<<stu_arr[i].score<<endl;
    }
    return 0;
}
编译和执行
 
结构体指针
#include<iostream>
#include<string>
using namespace std;
struct Student
{
    string name;
    int age;
    int score;
};
int main()
{
    struct Student s = {"张三",18,100};
    
    // 创建Student类型的指针
    Student* p = &s;
    // 用结构体类型的指针访问结构体的变量
    cout<<"姓名:"<<p->name<<"年龄: "<<p->age<<"分数: "<<p->score<<endl;
    return 0;
}
结构体嵌套结构体
#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 t;
    t.id = 1000;
    t.name = "老王";
    t.age = 50;
    // 把学生的值也设置一下
    t.stu.name = "小王";
    t.stu.age = 26;
    t.stu.score = 60;
    cout<<t.stu.name<<" "<<t.stu.age<<" "<<t.stu.score<<endl;
    return 0;
}

C++输出string类型必须引入 #include
# 使用输入命令输出报错
cout<<"姓名"<<s1.name<<"年龄"<<s1.age<<endl;
因为s1.name是string类型,C++输出string类型必须引入 #include<string>



















