引用变量

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

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

 

posted @ 2016-07-02 21:27  sarah_lxq  阅读(286)  评论(0编辑  收藏  举报