C++结构体作为函数参数传参

骑猪看日落 2023-02-20 07:50 102阅读 0赞
  1. #include<iostream>
  2. using namespace std;
  3. #include<string>
  4. //结构体
  5. struct Student {
  6. string name;
  7. int age;
  8. int score;
  9. }st3;
  10. /*
  11. *结构体作为函数参数传参
  12. */
  13. //值传递
  14. void printStufdent1(struct Student st3) {
  15. cout << "子函数" << endl;
  16. st3.age = 100;
  17. cout << "名字:" << st3.name << " 年龄:" << st3.age << " 分数:" << st3.score << endl;
  18. }
  19. //地址传递
  20. void printStufdent2(struct Student * p) {
  21. p->age = 200;
  22. cout << "子函数" << endl;
  23. cout << "名字:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl;
  24. }
  25. int main() {
  26. struct Student st1;
  27. st1.name = "zhangsan";
  28. st1.age = 18;
  29. st1.score = 60;
  30. //cout << "名字" << st1.name << "年龄" << st1.age << "分数" << st1.score<< endl;
  31. struct Student st2={"李四",20,70};
  32. // cout << "名字" << st2.name << "年龄" << st2.age << "分数" << st2.score<< endl;
  33. st3.name = "王五";
  34. st3.age = 19;
  35. st3.score = 59;
  36. printStufdent1(st3);
  37. cout << "main函数" << endl;
  38. cout << "名字:" << st3.name << " 年龄:" << st3.age << " 分数:" << st3.score << endl;
  39. printStufdent2(&st3);
  40. cout << "main函数" << endl;
  41. cout << "名字:" << st3.name << " 年龄:" << st3.age << " 分数:" << st3.score << endl;
  42. system("pause");
  43. }

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3l3bDQ3MDgxMjA4Nw_size_16_color_FFFFFF_t_70

从结果我们知道结构体作为函数的参数传参有两种形式

发表评论

表情:
评论列表 (有 0 条评论,102人围观)

还没有评论,来说两句吧...

相关阅读