引用

本文深入讲解了C++中引用的概念,解释了引用作为变量别名的工作原理及其注意事项,通过实例展示了如何使用引用进行变量间的操作。

引用就是别名。我们在定义时必须对其初始化。例如:

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 ;
}


程序运行结果:

根据上面的结果:我们可以印证上面讲的注意点。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值