123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- #include <iostream>
- //结构体作函数参数
- //将结构体作为参数向函数中传递
- //传递方式有两种
- //⚪值传递
- //⚪地址传递
- //定义学生的结构体
- #if(0)
- struct Student
- {
- //姓名
- std::string name;
- //年龄
- int age;
- //分数
- int score;
- };
- //打印学生信息的函数
- //1、值传递
- void printStudent1(struct Student s)
- {
- s.age = 100;
- std::cout << "子函数1中 姓名:" << s.name << "年龄:" << s.age << "分数:" << s.score << std::endl;
- }
- //2、地址传递
- void printStudent2(struct Student *p)
- {
- p->age = 200;
- std::cout << "子函数2中 姓名" << p->name << "年龄:" << p->age << "分数:" << p->score << std::endl;
- }
- int main()
- {
- //将学生传入到一个参数中,打印学生身上的所有信息
- //创建一个结构体变量
- struct Student s;
- s.name = "张三";
- s.age = 20;
- s.score = 85;
- //printStudent1(s);
- printStudent2(&s);
-
- std::cout << "main函数中打印 姓名:" << s.name << "年龄:" << s.age << "分数:" << s.score << std::endl;
- system("pause");
- return 0;
- }
- #endif
- //总结:如果不想修改主函数中的数据,用值传递,反之用地址传递
|