结构体
结构体的基本概念
结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
结构体的定义和使用
语法 struct 结构体名{结构体成员列表};
三种创建方式:
1.struct 结构体名 变量名
2.struct 结构体名 变量名 = {成员1值, 成员2值...}
3.定义结构体时顺便创建变量 //不常用
示例
//结构体变量创建方式1
struct student
{
//成员列表
string name;
int age;
int score;
};
//结构体变量创建方式2
struct student stu2 = {"李四", 16,56};
int main ()
{
struct student stu1;
stu1.name = "张三";
stu2.age = 18;
stu1.score = 100;
cout < "姓名: " << stu1.name << "年龄 :" << stu1.age << "分数: " << stu1.score << endl;
}
结构体数组
作用 : 将自定义的结构体放入到数组中方便维护
语法 :struct 结构体名 数组名【元素个数】= {{},{},{},...{}}
示例:
struct student
{
//成员列表
string name;
int age;
int score;
};
int mian ()
{
//结构体数组
struct student arr[3]=
{
{"zhangsan",18,80},
{"lisi", 25,86}
};
//给结构体数组中的元素赋值
arr[1].name = "zhaoliu";
//遍历结构体数组
for(int i = 0; i < 2 ;i++)
{
cout << "姓名: " << arr[i].name << endl;
}
结构体指针
作用 : 通过指针访问结构体中的成员
利用操作符 -> 可以通过结构体指针访问结构体属性
//结构体定义
struct student
{
//成员列表
string name ;
int age;
int score;
};
int main ()
{
//1.创建学生结构体变量
student s = {"zhangsan", 18 , 100};
//2.通过指针指向结构体变量
student * p = &s;
//3.通过指针访问结构体变量中的数据
cout << "姓名: " << p->name << "年龄" << p->age << "分数" << p->score << endl;
return 0;
结构体嵌套结构体
作用 : 结构体中的成员可以是另一个结构体
例如:每一个老师辅导一个学员,一个老师结构体中,记录一个学生的结构体
实例:
//学生结构体定义
struct student
{
//成员列表
string name ;
int age;
int score;
};
//教师结构体定义
struct teacher
{
int id;
string name;
int age;
struct student stu; // 子结构体 学生
结构体做函数参数
作用: 结构体作为参数像函数中传递
两种方式:
1.值传递
2.地址传递
实例:
struct student
{
//成员列表
string name ;
int age;
int score;
};
//值传递
void printStudent (student stu)
{
stu.age = 28;
cout << "子函数中姓名 "<< stu.name << "年龄"<< stu.age << endl;
}
//地址传递
void printStudent2(Student *stu)
{
stu->age = 28;
cout << "子函数中姓名 "<< stu->name << "年龄"<< stu->age << endl;
}
int mian ()
{
student stu = {"zhangsan", 18, 100};
//值传递
printStudent(stu);
cout << "主函数中 姓名: " << stu.name <<"年龄"<< stu。age << endl;
//地址传递
printStudent2(&stu);
cout << "主函数中 姓名 "<< stu->name << "年龄"<< stu->age << endl;
return 0;
}
如果不想修改主函数中的值,就用值传递,反之用地址传递