C++引用

C++引用

你是否因为看见&而崩溃?

举一下例子

int &a=b;
int *a;
a=&b;

哈哈哈哈,是不是有点小奔溃,让我来告诉你,你已经把引用和指针弄混淆了!!!

正题
引用变量是一个别名,它表示一个已经存在变量的另一个名字,一旦把引用初始化为某个变量,就可以使用该引用变量来等价于变量。

int &a=b;
//a等价于b

注意:

  • 不存在空引用,引用必须连接到一块合法的内存
//int &a;这是错误的,必须引用到一个合法的内存

在数据结构中,我们可以用引用来交换数据

#include<iostream>
using namespace std;
void swap(int &x,int &y);
int main()
{
	//设置局部变量
	int a=100;
	int b=200;
	
	cout<<"before swap of value of a\t"<<a<<endl; 
	cout<<"before swap of value of b\t"<<b<<endl;
	
	swap(a,b);
	
	cout<<"after swap of value of a\t"<<a<<endl; 
	cout<<"after swap of value of b\t"<<b<<endl;
	
	return 0;
}
void swap(int &x,int &y)
{
	int temp;
	temp=x;
	x=y;
	y=temp;
}

结果运行图
在这里插入图片描述
当然,数据结构也用指针来交换数据,可以看一下这个例子

#include<iostream>
using namespace std;
void swap(int *c,int *d);
int main()
{
	int a=10;
	int b=20;
	
	cout<<"before swap of value of a\t"<<a<<endl; 
	cout<<"before swap of value of b\t"<<b<<endl;
	
	swap(&a,&b);
	
	cout<<"after swap of value of a\t"<<a<<endl; 
	cout<<"after swap of value of b\t"<<b<<endl;
	
	return 0;
}
void swap(int *c,int *d)
{
	int temp;
	temp=*c;
	*c=*d;
	*d=temp;
}

结果图如下
在这里插入图片描述
这下明白了吧,点个赞再走啊,考研中抽时间撰写文章不容易啊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值