5、结构体作函数参数.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <iostream>
  2. //结构体作函数参数
  3. //将结构体作为参数向函数中传递
  4. //传递方式有两种
  5. //⚪值传递
  6. //⚪地址传递
  7. //定义学生的结构体
  8. #if(0)
  9. struct Student
  10. {
  11. //姓名
  12. std::string name;
  13. //年龄
  14. int age;
  15. //分数
  16. int score;
  17. };
  18. //打印学生信息的函数
  19. //1、值传递
  20. void printStudent1(struct Student s)
  21. {
  22. s.age = 100;
  23. std::cout << "子函数1中 姓名:" << s.name << "年龄:" << s.age << "分数:" << s.score << std::endl;
  24. }
  25. //2、地址传递
  26. void printStudent2(struct Student *p)
  27. {
  28. p->age = 200;
  29. std::cout << "子函数2中 姓名" << p->name << "年龄:" << p->age << "分数:" << p->score << std::endl;
  30. }
  31. int main()
  32. {
  33. //将学生传入到一个参数中,打印学生身上的所有信息
  34. //创建一个结构体变量
  35. struct Student s;
  36. s.name = "张三";
  37. s.age = 20;
  38. s.score = 85;
  39. //printStudent1(s);
  40. printStudent2(&s);
  41. std::cout << "main函数中打印 姓名:" << s.name << "年龄:" << s.age << "分数:" << s.score << std::endl;
  42. system("pause");
  43. return 0;
  44. }
  45. #endif
  46. //总结:如果不想修改主函数中的数据,用值传递,反之用地址传递