引用经常被用作函数参数,使得函数中的变量名成为调用程序中的变量的别名,通俗易懂的讲,就是将形参变成实参的别名。这种传递参数的方法称为按引用传递。
C语言只能按值传递,按值传递导致被调用函数使用程序的值的拷贝,因此C语言采用按指针传递的方式,避开按值传递的限制;而按引用传递允许被调用的函数能够访问调用函数中的变量。
下面举个简单的例子:
交换两个变量的值,比较一下使用引用和指针,还有按值传递参数的方法作为参考。
程序例子:
#include <iostream>
using namespace std;
void swap1(int & a, int & b);
void swap2(int *pa , int *pb);
void swap3(int a , int b);
int main(void)
{
int apple1 = 100;
int apple2 = 200;
cout << "apple1 = " << apple1 << endl;
cout << "apple2 = " << apple2 << endl;
//使用引用作为参数,按引用交换
cout << "Using references to swap contents: " << endl;
swap1(apple1,apple2);
cout << "apple1 = " << apple1 << endl;
cout << "apple2 = " << apple2 << endl;
//使用指针作为参数,按指针交换
cout << "Using pointers to swap contents: " << endl;
swap2(&apple1,&apple2);
cout << "apple1 = " << apple1 << endl;
cout << "apple2 = " << apple2 << endl;
//使用按值传递作为参数,按值交换
cout << "Using values to swap contents: " << endl;
swap3(apple1,apple2);
cout << "apple1 = " << apple1 << endl;
cout << "apple2 = " << apple2 << endl;
return 0;
}
void swap1(int & a , int & b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void swap2(int *pa , int *pb)
{
int temp;
temp = *pa;
*pa = *pb;
*pb = temp;
}
void swap3(int a , int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
运行结果:
apple1 = 100
apple2 = 200
Using references to swap contents:
apple1 = 200
apple2 = 100
Using pointers to swap contents:
apple1 = 100
apple2 = 200
Using values to swap contents:
apple1 = 100
apple2 = 200
--------------------------------
Process exited after 0.3331 seconds with return value 0
请按任意键继续. . .
其中交换函数必须能够修改调用程序中的变量的值。这就意味着按值传递变量是不管用的,因为函数讲交换原始变量的副本的内容,而不是变量本身的内容。