【C++笔记】八、结构体 [ 3 ]
8.5 结构体 嵌套 结构体
作用: 结构体中的成员可以是另一个结构体
- 先定义 子结构体 (内层结构体)
- 再定义 母结构体 (外层结构体)
#include<iostream>
using namespace std;
#include<string>
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.stu.name << " 学生年龄: " << t.stu.age
<< " 学生考试分数: " << t.stu.score<<endl;
system("pause");
return 0;
}
8.6 结构体做函数参数
作用 : 将结构体作为参数向函数中传递
传递方式有两种:
- 值传递
- 地址传递
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<string>
//定义学生结构体
struct student
{
string name;//姓名
//年龄
int age;
//分数
int score;
};
//打印学生信息函数
//1. 值传递
void printStudent1(struct student s)
{
s.age = 100;//改变函数内部值, 看外部是否改变
cout << "子函数1中打印 姓名: " << s.name << " 年龄: " << s.age << " 分数: " << s.score << endl;
}
//2. 地址传递
void printStudent2(struct student *p) {
p->age = 200;//改变函数内部值, 看外部是否改变
cout << "子函数2中打印 姓名: " << p->name << " 年龄: " << p->age << " 分数: " << p->score << endl;
//注意指针要用->访问
}
int main() {
//结构体做函数参数
//将学生传入到一个参数中,打印学生身上的所有信息
//创建结构体变量
struct student s;
s.name = "张三";
s.age = 20;
s.score = 85;
printStudent1(s);
printStudent2(&s);
cout << "main函数中打印 姓名: " << s.name << "年龄: " << s.age << "分数: " << s.score << endl;
}
总结: 如果不想修改主函数中的数据,用值传递,反之用地址传递