性质:
1.引用成为一个变量的引用之后,不能成为其他变量的引用。
#include <iostream>
using namespace std;
int main()
{
int a=10;
int& small_a=a;
cout<<a<<" "<<small_a<<endl;
cout<<&a<<" "<<small_a<<endl;
&small_a=c;//错误
return 0;
}
2.引用之前必须初始化且不能赋值为NULL;
#include<iostream>
using namespace std;
int main()
{
int b=10;
int &a=NULL;//错误
int &a=b;//正确
cout<<b<<endl;
return 0;
}
3.当引用常量时,必须加const修饰,表示被修饰的值不能更改
#include<iostream>
using namespace std;
int main()
{
const int& b=100;
b++;//错误
return 0;
}
应用:
#include<iostream>
using namespace std;
void swap(int& a,int& b);
int main()
{
int a=10;
int b=20;
swap(a,b);
return 0;
}
void swap(int& a,int& b)
{
int t=a;
a=b;
b=t;
cout<<a<<" "<<b<<endl;
}
描述:
通过函数调用,将实参a,b传给形参a,b,形参是引用形式,这种方式方便快捷,直接改变实参的值,相对于地址传参,大大节省了内存空间,提高效率。