作用:将结构体作为参数向函数中传递
传递的方式有两种:
- 值传递
- 地址传递
示例:
#include <iostream>#include <string>using namespace std;// 定义学生结构体struct student {// 姓名string name;// 年龄int age;// 分数int score;};// 打印学生信息函数// 1.值传递void printStudent1(struct student s) {s.age = 100;cout << "子函数中 姓名:" << 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(void) {// 结构体做函数参数// 将学生传入到一个参数中,打印学生身上的所有信息// 创建结构体变量struct student s;s.name = "张三";s.age = 19;s.score = 96;//printStudent1(s);printStudent2(&s);cout << "main函数中打印 姓名:" << s.name << " 年龄:" << s.age << " 分数:" << s.score << endl;return 0;}
总结:
- 如果不想修改主函数中的数据,用值传递,反之用地址传递。
