- #include <iostream>
- using namespace std;
- int main(){
- int x,y;
- cin >> x >> y;
- int temp;
- cout << "Before swap a and y:" << endl;
- cout << x << " "<< y << endl;
- temp = x;
- x = y;
- y = temp;
- cout << "After swap x and y:" << endl;
- cout << x << " " << y << endl;
- return 0;
- }
这是一段用于交换输入的两个整数的值的代码, 测试一下
输入数据:
13 21
输出结果:
- Before swap a and y:
- 13 21
- After swap x and y:
- 21 13
没有任何问题
因为要交换多组数据, 我们把交换的代码改写成用 函数 实现
- #include <iostream>
- using namespace std;
- void swap(int x, int y);
- int main(){
- int x,y;
- cin >> x >> y;
- cout << "Before swap a and y:" << endl;
- cout << x << " " << y << endl;
- swap(x,y);
- cout << "After swap x and y:" << endl;
- cout << x << " " << y << endl;
- return 0;
- }
- void swap(int x, int y){
- int temp;
- temp = x;
- x = y;
- y = temp;
- }
输入数据:
13 21
输出结果:
- Before swap a and y:
- 13 21
- After swap x and y:
- 13 21
改写后的代码并没有交换 x,y 的值, 回想下刚刚的思路
其实, 这种思路数据是错误的
C++ 的函数的参数方式是 值传递 ,swap 函数在被调用时, 系统会给形参分配空间, 用实参的值初始化 swap 的 x,y
通过上图我们可以看到, 函数的值传递是单向的 (注意: 变量名只是个代号, 重要的是它所指向的东西)
那么要怎么样才能在 swap 函数交换 main 函数的 x,y 呢?
我们可以使用 引用传递 的方式对函数的参数进行传递
引用 是一种 特殊类型 的 变量 , 相当于给 变量 起一个 别名 , 来看下下面的代码
- /*
- * 摘 要: 引用传递示例
- * 作 者: 水汐音
- * 完成日期: 2018 年 2 月 27 日
- */
- #include <iostream>
- using namespace std;
- int main(){
- int x,y;
- x = 3;
- y = 4;
- cout << "Before:" << endl;
- cout << x << " " << y << endl;
- int &b = x;
- b = y;
- cout << "After:" << endl;
- cout << x << " " << y << endl;
- return 0;
- }
输出结果
- Before:
- 3 4
- After:
- 4 4
可以看到, b 作为 x 的别名, 改变变量 b 的值 就是改变变量 x 的值
打个比方, 我们假设 李华 的小名是 小华,
别人寄给了小华华一个刀片, 跟别人寄给李华一个刀片是一样的
同理, 把 y 的值给了 b, 跟把 y 的值给了 x 是一样的
通过 引用传递 我们把 swap 函数 debug
- #include <iostream>
- using namespace std;
- void swap(int &x, int &y);
- int main(){
- int x,y;
- cin >> x >> y;
- cout << "Before swap a and y:" << endl;
- cout << x << " " << y << endl;
- swap(x,y);
- cout << "After swap x and y:" << endl;
- cout << x << " " << y << endl;
- return 0;
- }
- void swap(int &x, int &y){
- int temp;
- temp = x;
- x = y;
- y = temp;
- }
输入数据:
13 21
输出结果:
- Before swap a and y:
- 13 21
- After swap x and y:
- 21 13
成功交换
注意: & 既可以表示引用, 又可以 表示取地址符
- int a = 9;
- int &na = a; // 定义引用
- int *p = &a; // 取地址
- 2018-02-27
水汐音
来源: http://www.bubuko.com/infodetail-2509339.html