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;
}
结果图如下
这下明白了吧,点个赞再走啊,考研中抽时间撰写文章不容易啊