本段程序主要是完成值交换函数,包括基于值传递、基于地址传递以及引用作为函数参数三个子函数。
尤其值得关注如何把引用作为函数参数,进而实现数值交换。这一段的代码如下:
void swap_y(int &a, int &b)
{int temp = a;a = b;b = temp;
}
全部代码以及运行效果如下:可以发现,仅仅是值传递,不能使主函数内实现数值交换,其余两种可以实现。
#include <iostream>using namespace std;void swap_value(int a, int b)
{int temp = a;a = b;b = temp;
}void swap_ptr(int *a, int *b)
{int temp = *a;*a = *b;*b = temp;
}void swap_y(int &a, int &b)
{int temp = a;a = b;b = temp;
}int main(int argc, char **argv)
{int num1 = 10, num2 = 20;int x = 1, y = 2;int a = 100, b = 200;// 1 值传递cout << "值传递前:" << endl;cout << "num1 = " << num1 << endl;cout << "num2 = " << num2 << endl;swap_value(num1,num2);cout << "值传递后:" << endl;cout << "num1 = " << num1 << endl;cout << "num2 = " << num2 << endl;cout << endl;// 2 地址传递cout << "地址传递前:" << endl;cout << "x = " << x << endl;cout << "y = " << y << endl;swap_ptr(&x, &y);cout << "地址传递后:" << endl;cout << "x = " << x << endl;cout << "y = " << y << endl;cout << endl;// 3 引用cout << "引用前:" << endl;cout << "a = " << a << endl;cout << "b = " << b << endl;swap_y(a,b);cout << "引用后:" << endl;cout << "a = " << a << endl;cout << "b = " << b << endl;cout << endl;return 0;
}