引用就是别名。我们在定义时必须对其初始化。例如:
int num = 2;
int &rnum = num ;//rnum是num的别名,这两个变量是一个变量,只是他们的名字不同而已
注意:
1、别名rnum前面的&不是取地址操作符,而是引用运算符,虽然他们符号相同,但功能却不一样。
2、对别名rnum的操作,实际上就是对变量num的操作,因为它们的地址是相同。
rnum = rnum + 2 ;
rnum加2后,rnum的的值是4,并且num的值也是4。
请看下面的一个例子:
#include <iostream>
using namespace std;
int main()
{
int a = 2 ;
int &ra = a ;
cout << "取a和ra的地址\n" ;
cout << "&a:\t" << &a << endl ;
cout << "&ra:\t" << &ra << endl ;
cout << endl ;
cout << "输出a和ra的值\n" ;
cout << "a:\t" << a << endl ;
cout << "ra:\t" << ra << endl ;
cout << endl ;
a = a + 2 ;
cout << "a加2后,输出a和ra的值\n" ;
cout << "a:\t" << a << endl ;
cout << "ra:\t" << ra << endl ;
cout << endl ;
ra = ra + 2 ;
cout << "ra加2后,再输出a和ra的值\n" ;
cout << "a:\t" << a << endl ;
cout << "ra:\t" << ra << endl ;
cout << endl ;
int b = 6 ;
ra = b ;
cout << "将变量b的值赋给ra后,输出a和ra以及b的地址\n" ;
cout << "&a:\t" << &a << endl ;
cout << "&ra:\t" << &ra << endl ;
cout << "&b:\t" << &b << endl ;
cout << endl ;
cout << "输出a、ra、b的值\n" ;
cout << "a:\t" << a << endl ;
cout << "ra:\t" << ra << endl ;
cout << "b:\t" << b << endl ;
cout << endl ;
ra = 1 ;
cout << "ra赋值为1后,再输出a、ra、b的值\n" ;
cout << "a:\t" << a << endl ;
cout << "ra:\t" << ra << endl ;
cout << "b:\t" << b << endl ;
cout << endl ;
return 0 ;
}
程序运行结果:
根据上面的结果:我们可以印证上面讲的注意点。
本文深入讲解了C++中引用的概念,解释了引用作为变量别名的工作原理及其注意事项,通过实例展示了如何使用引用进行变量间的操作。
3708

被折叠的 条评论
为什么被折叠?



