8. 结构体
结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
8.1结构体定义和使用
语法:struct 结构体名{ 结构体成员列表 };
通过结构体创建变量的方式有三种:
- struct 结构体名 变量名
- struct 结构体名 变量名={成员1值,成员2值......}
- 定义结构体时顺便创建变量
#include <iostream>
using namespace std;
# include "swap.h"
# include <string>
//1.创建学生数据类型:(学生包括(姓名,年龄,分数))
//自定义数据类型,一些类型集合组成的一个类型
//语法 struct 类型名称{ 成员列表 }
struct Student {
//成员列表
//姓名
string name;
//年龄
int age;
//分数
int score;
}s3
//2.3 在定义结构体时顺便创建结构体变量;
//2.通过学生类型创建出具体的学生
int main()
{
//2.1 struct Student s1
struct Student s1;
s1.name = "张三";
s1.age = 18;
s1.score = 90;
cout<<"姓名:" <<s1.name<<"年龄:"<<s1.age <<"分数:"<<s1.score << endl;
//2.2 struct Student s2={ ... }
struct Student s2 = {"李四",19,80};
cout << "姓名:" << s2.name << "年龄:" << s2.age << "分数:" << s2.score << endl;
system("pause");
return 0;
}
注意:用到string类型结构,要给文件开头写 #include <string>
创建变量时,struct关键字可以省略
8.2 结构体数组
作用:将自定义的结构体放入到数组中方便维护
语法:struct 结构体名 数组名 [元素个数]={{},{},...{}}
示例:
#include <iostream>
using namespace std;
# include "swap.h"
# include <string>
//1.创建学生数据类型:(学生包括(姓名,年龄,分数))
//自定义数据类型,一些类型集合组成的一个类型
//语法 struct 类型名称{ 成员列表 }
struct Student {
//成员列表
//姓名
string name;
//年龄
int age;
//分数
int score;
}s3;
//2.3 在定义结构体时顺便创建结构体变量;
//2.通过学生类型创建出具体的学生;
int main()
{
struct Student arr[3] = {
{"张三",18,90},
{"李四",19,80},
{"王五",20,92}
};
system("pause");
return 0;
}
8.3 结构体指针
作用:通过指针访问结构体中的成员
利用操作符->可以通过结构体指针访问结构体属性
示例:
//1. 创建学生结构体变量
struct Student s = {"张三",18,100};
//2. 通过指针指向结构体变量
Student* p = &s;
p->name = "张思";
8.5 结构体嵌套结构体
作用:结构体中的成员可以是另一个结构体
例如:每个老师辅导一个学员,一个老师的结构体中,记录一个学生的结构体
示例:
struct Student {
string name;
int age;
int score;
};
struct teacher {
int id;
string name;
int age;
struct Student stu;
};
8.6 结构体做函数参数
作用:将结构体作为参数向函数中传递
传递方式有两种:值传递和地址传递
示例:
/值传递
void printstudent1(student stu) {
stu.age = 28;
cout<<"子函数中 姓名:"<<stu.name<<"年龄:"<<stu.age<<"分数:"<<stu.score << endl;
}
//地址传递
void printstudent2(struct student * p) {
p->age = 18;
cout << "子函数中 姓名:" << p->name << "年龄:" << p->age << "分数:" << p->score << endl;
}
8.7 结构体中const使用场景
作用:用const来防止误操作
示例:
//将函数中的形参改为指针,可以减少内存空间,而且不会复制出新的副本出来
void printstudent2(const student * p) {
//s->age=150; //经过const修饰的结构体变量,其成员值是不可更改的
cout << "子函数中 姓名:" << p->name << "年龄:" << p->age << "分数:" << p->score << endl;
}