结构体做函数参数
作用:将结构体作为参数向指针中传递
传递方式有2种:
(1)值传递:在值传递中,修改形参,实参不会改变
/*打印输出函数*/
//1.值传递
void printStudent(struct student stu)
{
stu.age = 40; //在值传递中,修改形参,实参不会改变
cout << "值传递子函数中:" << endl;
cout << "姓名: " << stu.name << " 年龄: " << stu.age << " 分数:" << stu.score <<endl;
}
(2)地址传递:在地址传递中,修改形参,实参也会改变
//2.地址传递
void printStudent2(struct student * p)
{
p->age = 30; //在地址传递中,修改形参,实参也会改变
cout << "地址传递子函数中:" << endl;
cout << "姓名: " << p->name << " 年龄: " << p->age << " 分数:" << p->score << endl;
}
原代码:
#include<iostream>
using namespace std;
#include<string>
void printStudent(struct student stu);
/*1.定义一个结构体*/
struct student
{
string name;
int age;
int score;
}s1;
/*打印输出函数*/
//1.值传递
void printStudent(struct student stu)
{
stu.age = 40; //在值传递中,修改形参,实参不会改变
cout << "值传递子函数中:" << endl;
cout << "姓名: " << stu.name << " 年龄: " << stu.age << " 分数:" << stu.score <<endl;
}
//2.地址传递
void printStudent2(struct student * p)
{
p->age = 30; //在地址传递中,修改形参,实参也会改变
cout << "地址传递子函数中:" << endl;
cout << "姓名: " << p->name << " 年龄: " << p->age << " 分数:" << p->score << endl;
}
int main()
{
struct student stu;
stu.name = "小叶";
stu.age = 22;
stu.score = 99;
// printStudent(stu); //值传递
printStudent2(&stu); //地址传递
cout << "在main函数中打印输出:" << endl;
cout << "姓名: " << stu.name << " 年龄: " << stu.age << " 分数:" << stu.score << endl;
return 0;
}