作用:将结构体作为参数向函数中传递

传递的方式有两种:

  • 值传递
  • 地址传递

示例:

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. // 定义学生结构体
  5. struct student {
  6. // 姓名
  7. string name;
  8. // 年龄
  9. int age;
  10. // 分数
  11. int score;
  12. };
  13. // 打印学生信息函数
  14. // 1.值传递
  15. void printStudent1(struct student s) {
  16. s.age = 100;
  17. cout << "子函数中 姓名:" << s.name << " 年龄:" << s.age << " 分数:" << s.score << endl;
  18. }
  19. // 2.地址传递
  20. void printStudent2(struct student* p) {
  21. p->age = 200;
  22. cout << "子函数2中 姓名:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl;
  23. }
  24. int main(void) {
  25. // 结构体做函数参数
  26. // 将学生传入到一个参数中,打印学生身上的所有信息
  27. // 创建结构体变量
  28. struct student s;
  29. s.name = "张三";
  30. s.age = 19;
  31. s.score = 96;
  32. //printStudent1(s);
  33. printStudent2(&s);
  34. cout << "main函数中打印 姓名:" << s.name << " 年龄:" << s.age << " 分数:" << s.score << endl;
  35. return 0;
  36. }

总结:

  • 如果不想修改主函数中的数据,用值传递,反之用地址传递。