引用时变量的别名,可以像变量一样赋值,也可将其用于运算表达式。请看下面测试程序代码:
#include <iostream>
using namespace std;
int t1;
int &t2 = t1;
int main()
{
t1 = 1000;
cout << t2 << endl;
t2++;
cout << t1 << endl;
}
直接执行的结果如下:
t2是t1的引用,或者说t2是t1的别名,改变t1的值,实际上就是改变t2的值,改变t2的值也就是改变t1的值,或者说是改变同一内存区间的值。在上面程序中再加一行代码,如下:
#include <iostream>
using namespace std;
int t1;
int &t2 = t1;
int main()
{
t1 = 1000;
cout << t2 << endl;
t2++;
cout << t1 << endl;
cout << t1*5 << endl;
cout << t2 * 10 << endl;
}
直接执行的结果如下:
可以看出引用也可像变量一样使用。在上面程序中再加一行代码,如下:
#include <iostream>
using namespace std;
int t1;
int &t2 = t1;
int main()
{
t1 = 1000;
cout << t2 << endl;
t2++;
cout << t1 << endl;
cout << t1*5 << endl;
cout << t2 * 10 << endl;
cout << &t1 << endl;
}
直接执行的结果如下:
在上面程序中再加一行代码,如下:
#include <iostream>
using namespace std;
int t1;
int &t2 = t1;
int main()
{
t1 = 1000;
cout << t2 << endl;
t2++;
cout << t1 << endl;
cout << t1*5 << endl;
cout << t2 * 10 << endl;
cout << &t1 << endl;
cout << &t2 << endl;
}
直接执行的程序结果会怎样呢?结果如下:
对t1与t2取地址,结果指像同一地址。已定义了变量,再去搞个引用似乎意义不大,像上面这样使用确实有点多此一举。请再看下面程序:
#include <iostream>
using namespace std;
int t1;
int t2;
void swap(int x, int y)
{
int tem = x;
x = y;
y = tem;
}
int main()
{
t1 = 1000;
t2 = 2000;
swap(t1, t2);
cout << t1 << endl;
cout << t2 << endl;
}
直接执行的结果如下:
没法实现t1、t2值的交换,因为C函数是按值传递,即传递的是变量的值,并不传递变量的地址,没法改变变量的值。再在上面的程序中加一个交换函数swap1,代码如下:
#include <iostream>
using namespace std;
int t1;
int t2;
void swap(int x, int y)
{
int tem = x;
x = y;
y = tem;
}
void swap1(int &x, int &y)
{
int tem = x;
x = y;
y = tem;
}
int main()
{
t1 = 1000;
t2 = 2000;
swap(t1, t2);
cout << t1 << endl;
cout << t2 << endl;
swap1(t1, t2);
cout << t1 << endl;
cout << t2 << endl;
}
直接执行的结果如下:
调用函数swap1实现了t1、t2值的交换。再在上面的程序中加一个交换函数swap2,代码如下:
#include <iostream>
using namespace std;
int t1;
int t2;
void swap(int x, int y)
{
int tem = x;
x = y;
y = tem;
}
void swap1(int &x, int &y)
{
int tem = x;
x = y;
y = tem;
}
void swap2(int *x, int *y)
{
int tem = *x;
*x = *y;
*y = tem;
}
int main()
{
t1 = 1000;
t2 = 2000;
swap(t1, t2);
cout << t1 << endl;
cout << t2 << endl;
cout << endl;
swap1(t1, t2);
cout << t1 << endl;
cout << t2 << endl;
cout << endl;
swap2(&t1, &t2);
cout << t1 << endl;
cout << t2 << endl;
cout << endl;
}
直接执行的结果如下:
可以看出交换函数swap2也可实现数据交换,swap1函数参数使用了引用,swap2函数参数使用了指针。swap2函数较swap1函数要复杂得多。引用也实现了变量地址传递,个人感觉函数定义时要实现地址传递,又不想使用指针,就得使用引用,这就是引用类型的最大用处。。