作用:将结构体作为参数箱函数中传递
传递的方式:
- 值传递:形参修饰后,不会改变实参的值。
- 地址传递:形参发生改变实参也会改变。
#include<iostream>
#include<string>
using namespace std;
//定义学生结构体
struct Student {
string name;
int age;
int score;
};
//打印学生信息的函数
//1、值传递
void PrintStuInfo(struct Student s)
{
s.age = 100;
std::cout << "name: " << s.name << " age:" << s.age << " score:" << s.score << endl;
}
//地址传递,外侧的数据也会发生变化
void PrintStuInfo1(struct Student *p)
{
p->age = 200;
std::cout << "PrintStuInfo1 name: " << p->name << " age:" << p->age << " score:" << p->score << endl;
}
//结构体做参数
int main()
{
struct Student s = { "Tom",20,100 };
PrintStuInfo(s);
cout << "值传递" << endl;
std::cout << "name: " << s.name << " age:" << s.age << " score:" << s.score << endl;
PrintStuInfo1(&s);
cout << "地址传递" << endl;
std::cout << "name: " << s.name << " age:" << s.age << " score:" << s.score << endl;
system("pause");
return 0;
}