一、结构体的基本概念
属于用户自定义的数据类型,允许用户存储不同的数据类型
二、结构体的定义和使用
语法:struct 结构体名{结构体成员列表};
struct Student
{
//成员列表
string name;
int age;
int score;
};
通过结构体创建变量的方式有三种:
- struct 结构体名 变量名
Struct Student s1;
S1.name = "张三";
S1.age = 19;
S1.score = 100;
- struct 结构体名 变量名 = {成员1值,成员2值,…}
Struct Student s2 = {
"李四", 19, 80 };
- 定义结构体时顺便创建变量
Struct Student
{
}s3;
备注:
• 结构体定义的时候,关键字struct不可以省略
• 结构体变量创建的时候,关键字struct可以省略
• 结构体变量利用 操作符“.” 来访问成员
三、结构体指针
作用:通过指针访问结构体中的成员
利用 操作符-> 可以通过结构体指针访问结构体属性
e.g.结果由s.name 变成 p->name
student s = {
"张三", 18, 100 };
student *p = &s;
四、结构体嵌套结构体
作用:结构体中的成员可以是另一个结构体
e.g. 老师辅导学生,老师结构体记录学生的结构体
//学生结构体定义
struct student
{
string name;
int age;
int score;
};
//老师结构体定义
struct teacher
{
int id;
string name;
int age;
struct student stu;
};
int main()
{
struct teacher t1;
t1.id = 10000;
t1.name = "老王";
t1.age = 40;
t1.stu.name = "张三";
t1.stu.age = 18;
t1.stu.score = 100;
}
五、结构体做函数参数
注意值传递和地址传递的区别
//定义打印学生信息的函数
//1.值传递(不会修改实参)
void printStudent1(struct student s)
{
s.age = 100;
cout <<