C++中,引用(reference)是已存在变量的别名(alias),通过引用,可间接访问变量,指针也可以,但引用在使用上更加安全。引用的主要用途是描述函数的参数和返回值,特别是传递较大的数据变量。
定义:
语法格式:
数据类型 & 引用变量名 = 变量名;
eg:
int x;
int &refx=x;
运用引用交换两个变量的值。
/**
* 行有余力,则来刷题!
* 博客链接:http://blog.youkuaiyun.com/hurmishine
*
*/
#include <iostream>
#include <cstdio>
using namespace std;
void Myswap(int &x,int &y)
{
int t=x;
x=y;
y=t;
}
int main()
{
int x=10,y=20;
cout<<"x="<<x<<",y="<<y<<endl;
Myswap(x,y);
cout<<"x="<<x<<",y="<<y<<endl;
return 0;
}
引用作为函数参数和返回值。
/**
* 行有余力,则来刷题!
* 博客链接:http://blog.youkuaiyun.com/hurmishine
*
*/
#include <iostream>
#include <cstdio>
using namespace std;
void fun(int x,int &y)//函数参数为引用
{
y=x;
}
int &sum(int x,int y)//函数返回值为引用
{
int z=x+y;
return z;
//注:以上改为: return x+y;则无法编译
}
int main()
{
int x=10;
int y=20;
int &z=y;//引用,z的值与y绑定,y改变则x也一起改变,反之亦然
cout<<"x="<<x<<",y="<<y<<endl; //x=10,y=20
cout<<"z="<<z<<endl; //z=20
fun(x,y);
cout<<"x="<<x<<",y="<<y<<endl; //x=10,y=10
cout<<"z="<<z<<endl; //z=10
z=50;
cout<<"x="<<x<<",y="<<y<<endl; //x=10,y=50
cout<<"z="<<z<<endl; //z=50
y=100;
cout<<"x="<<x<<",y="<<y<<endl;//x=10,y=100
cout<<"z="<<z<<endl;//100
//函数返回值为引用,可作为左值参与运算,但他本身的值不发生改变。
int a=10,b=20;
cout<<sum(a,b)<<endl; //30
cout<<--sum(a,b)<<endl; //29
cout<<++sum(a,b)<<endl; //31
cout<<sum(a,b)--<<endl; //30
cout<<sum(a,b)++<<endl; //30
sum(a,b)+=10;
cout<<sum(a,b)<<endl;//30
return 0;
}