码迷,mamicode.com
首页 > 其他好文 > 详细

引用变量

时间:2016-07-02 22:40:17      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

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

声明一个引用变量应在变量名前放置一个“&”。如: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;
}

 

引用变量

标签:

原文地址:http://www.cnblogs.com/sarah-lxq/p/5636074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!