C++中关于函数的引用

时间:2024-01-15 16:08:02

  这一块知识最常见的疑问就是:

#include <iostream>
#include <cstring>
using namespace std; int a[50];
int& fun(int& x)
{
return x;
}
int main()
{
int n;
while(cin>>n)
{
int i;
int tmp;
for(i = 1;i <= n;i++) {
cin>>tmp;
/*normal assignment way*/
//a[i] = tmp;
fun(a[i]) = tmp;
}
for(i = 1;i <= n-1;i++)
cout<<a[i]*2<<' ';
cout<<a[i]*2<<endl;
}
return 0;
}

形如这样的程序,在进行赋值操作的时候,为啥fun函数的返回值可以接受一个赋值呢?

要搞明白这个问题,我们不妨先来考虑另一个问题,来看code:

#include <stdio.h>
char *RetMemory()
{
char p[]="hello world\n";
return p;
}
int main( )
{
char *str=NULL;
str=RetMemory();
printf(str);
   return 0;
}

str并不能够顺利输出“hello world\n”,因为那是在fun函数中的一个临时变量,在fun函数的调用结束后他的空间就自动被销毁了,这就引出了我们的问题,怎样才能将函数内的变量返回回去?其实很简单,我们只要在一开始接受参数的时候用引用即可,即我们的形参是引用,然后返回的值也是引用,这样直观的来看我们会发现函数就像一个管道,起到了传输变量的作用

因此我们就不难理解为什么对左右移运算符的重载函数的返回类型和第一个参数的类型都要设置成引用:

ostream & operate <<(ostream &output, Complex &c)//定义流提取运算符“<<”重载函数
{
output<<”(”<<c.real<<”+”<<c.imag<<”i)”<<endl;
return output;
}