引用变量

引用变量是一种特殊类型的变量,将函数形参声明为此种类型的变量,形参将成为原变量的一个引用(而不是拷贝)。一个引用变量的实质是另一个变量的一个别名,任何对引用变量的改变实际上都会作用到原变量上。

声明一个引用变量应在变量名前放置一个“&”。如:int &refVar;  int & refVar;  int& refVar;

#include<iostream>    
using namespace std;

int main()
{
int count = 1;
int &refCount = count;                                                //声明一个引用变量,它只不过是count 的一个别名而已,实际上两者共享相同的内存空间;
refCount++;

cout << "count is " << count << endl;
cout << "refCount is " << refCount << endl;
return 0;
}

用引用变量实现swap 函数:

#include<iostream>
using namespace std;
void swap(int &, int &);
int main()
{
int num1 = 1;
int num2 = 2;
cout << "Before invoking the swap function,num1 is "<<
num1 << " and num2 is " << num2 << endl;
swap(num1,num2);

cout << "After invoking the swap function,num1 is " <<
num1 << " and num2 is " << num2 << endl;
return 0;
}

void swap(int &n1, int &n2){
int temp;
temp = n1;
n1 = n2;
n2 = temp;
return;
}

注:按引用方式传参时,形参和实参的类型必须完全相同。如:

#include<iostream>
using namespace std;

void f(double &p){
p++;
}
int main()
{
double x = 1;
int y = 1;                              // 变量y 的类型与 引用变量p的类型不一致,会出现error;
f(x);
f(y);
cout << "x is " << x << endl;
cout << "y is " << y << endl;


return 0;
}

 

转载于:https://www.cnblogs.com/sarah-lxq/p/5636074.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值