1、值传递:值传递中值的改变不会影响主函数中的值。
#include<iostream>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void printStudents(student s)
{
//值传递:他的值的改变不会改变主函数的值
s.age = 20;
cout << "学生的姓名:" << s.name << " 年龄:" << s.age << " 得分:" << s.score << endl;
}
int main()
{
student s = { "张三",23,80 };
printStudents(s);
cout << "主函数中的学生姓名:" << s.name << " 年龄:" << s.age << " 得分:" << s.score << endl;
system("pause");
return 0;
}
可以看到上述printStudents中s.age = 20;但是他并没有改变主函数中的age值;结果如下所示
2、地址传递:值改变会影响到主函数中的值
为了防止误操作,我们使用const
#include<iostream>
using namespace std;
//const防止误操作
struct student
{
string name;
int age;
int score;
};
void printStudents(const student *s)
{
//地址传递,使用了const防止误操作,所以会提示错误
//p->age = 20;
cout << "学生的姓名:" << s->name << " 年龄:" << s->age << " 得分:" << s->score << endl;
}
int main()
{
student s = { "张三",23,80 };
printStudents(&s);
cout << "主函数中的学生姓名:" << s.name << " 年龄:" << s.age << " 得分:" << s.score << endl;
system("pause");
return 0;
}
使用了const防止误操作,而且使用指针操作的话,可以节省内存空间!
结果如下: