结构体做函数参数
作用:将结构体作为参数向函数只能够传递 传递方式有两种: * 值传递 * 地址传递
代码示例:
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void printStudent1(struct student s)
{
s.age = 100;
cout << "子函数中 姓名:" << s.name
<< " 年龄:" << s.age
<< " 分数:" << s.score << endl;
}
void printStudent2(struct student *p)
{
p->age = 200;
cout << " 子函数2中 姓名:" << p->name
<< " 年龄:" << p->age
<< " 分数:" << p->score << endl;
}
int main()
{
struct student s;
{
s.name = "张三";
s.age = 21;
s.score = 85;
printStudent2(&s);
cout << "main函数中打印 姓名:" << s.name
<< " 年龄:" << s.age
<< " 分数:" << s.score << endl;
};
return 0;
}
总结:如果不想修改主函数中的数据,用值传递,反之用地址传递
|