8.4结构体指针
作用:通过指针访问结构体中的成员
利用操作符->可以通过结构体指针访问结构体属性
#include<iostream>
using namespace std;
//结构体定义
struct student
{
//成员列表
string name;//姓名
int age;// 年龄
int score;//分数
};
int main() {
//1,创建结构体变量
student s = { "张三",18,100 };
//2,通过指针指向结构体变量
student* p = &s;
//3,通过指针访问结构体变量中的数据
cout << "姓名:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl;
}
总结:结构体指针可以通过->操作符来访问结构体中的成员
8.5结构体嵌套结构体
作用:结构体中的成员可以是另一个结构体
例如:每一个老师辅导一个学员,一个老师的结构体中,记录一个学生的结构体
实例:
#include<iostream>
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 = 10000;
t.name = "老王";
t.age = 50;
t.stu.name = "小王";
t.stu.age = 20;
t.stu.score = 60;
cout << "老师姓名:" << t.name << " 老师编号:" << t.id << " 老师年龄:" << t.age << " 老师辅导的学生姓名:"
<< t.stu.name << " 学生年龄:" << t.stu.age << " 学生的考试分数:" << t.stu.score << endl;
}
8.6结构体做函数参数
作用:将结构体作为参数向函数中传递
传递方式有两种:
1,值传递
2,地址传递
示例:
#include<iostream>
using namespace std;
//结构体定义
struct student
{
//成员列表
string name;//姓名
int age;// 年龄
int score;//分数
};
//打印学生信息函数
//1,值传递
void printstuendt1(struct student s)
{
cout << "子函数1中 姓名:" << s.name << "分数:" << s.score << endl;
}
//2,地址传递
void printstudent2(struct student* p) {
cout << "子函数2中 姓名:" << p->name << "分数:" << p->score << endl;
}
int main() {
struct student s;
s.name = "张三";
s.age =20;
s.score = 85;
printstuendt1(s);
printstudent2(&s);
cout << "main函数中打印 姓名:" << s.name << "年龄:" << s.age << "分数:" << s.score << endl;
}
注意:
1)当我们在值传递
void printstuendt1(struct student s)
{
cout << "子函数1中 姓名:" << s.name << "分数:" << s.score << endl;
}
中加入s.age=100时
输出
在main中值并没有改变
2)当我们在地址传递
void printstudent2(struct student* p) {
cout << "子函数2中 姓名:" << p->name << "分数:" << p->score << endl;
}
中加入p->age=100;时输出
main中的值发生了改变