赞
踩
1、值传递
值传递在形参中改变参数的值不会改变实参中参数的值
2、地址传递
地址传递在形参中改变函数的参数会同时改变实参中的参数值
3、引用传递
引用传递在形参中改变函数的参数会同时改变实参中的参数值
下面代码充分显示了三种传递的区别:
- #include <iostream>
- #include<string>
- using namespace std;
-
- struct Student {
- string name;
- int age;
- int score;
- };
- void Student1(struct Student s) {
- //值传递
- s.age = 100;
- cout << "值传递后Student1中的值" << endl;
- cout << "姓名:" << s.name << endl;
- cout << "年龄:" << s.age << endl;
- cout << "成绩:" << s.score << endl;
- cout << endl;
- }
- void Student2(struct Student * p) {
- //地址传递
- p->age = 200;
- cout << "地址传递后Student2的值" << endl;
- cout << "姓名:" << p->name << endl;
- cout << "年龄:" << p->age << endl;
- cout << "成绩:" << p->score << endl;
- cout << endl;
- }
- void Student3(struct Student &s) {
- //引用传递
- s.age = 100;
- cout << "值传递后Student1中的值" << endl;
- cout << "姓名:" << s.name << endl;
- cout << "年龄:" << s.age << endl;
- cout << "成绩:" << s.score << endl;
- cout << endl;
- }
- int main()
- {
- struct Student s;
- s.name = "张三";
- s.age = 16;
- s.score = 99;
-
- cout << "main函数中的值" << endl;
- cout << "姓名:" << s.name << endl;
- cout << "年龄:" << s.age << endl;
- cout << "成绩:" << s.score << endl;
- cout << endl;
-
- Student1(s);//对s进行值传递
-
- cout << "值传递后main函数中的值" << endl;
- cout << "姓名:" << s.name << endl;
- cout << "年龄:" << s.age << endl;
- cout << "成绩:" << s.score << endl;
- cout << endl;
-
- Student2(&s);//对s进行地址传递,需要加上取地址符
-
- cout << "地址传递后main函数中的值" << endl;
- cout << "姓名:" << s.name << endl;
- cout << "年龄:" << s.age << endl;
- cout << "成绩:" << s.score << endl;
- cout << endl;
-
- Student3(s);//对s进行引用传递
-
- cout << "引用传递后main函数中的值" << endl;
- cout << "姓名:" << s.name << endl;
- cout << "年龄:" << s.age << endl;
- cout << "成绩:" << s.score << endl;
- cout << endl;
-
- return 0;
- }
结果显示:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。