此代码,我想了解在原型中使用引用的必要性,如果不使用该引用会发生什么?
#include<iostream>
using namespace std;
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() ;
cout<<fun();
return 0;
}
这里没有“参考功能”。 &
是返回类型的一部分,最好写成
int& fun() {...
该函数正在返回引用,以便您可以执行
int main()
{
fun() = 6;
cout<<fun(); // will print 6
return 0;
}
注意,在大多数情况下,返回对函数局部变量的引用是错误的。在这里很好的原因是x
为static
,这意味着:它将仅被初始化一次,并在函数调用之间保持其值。
例如,此函数将返回调用次数的计数器:
int count_me() {
static int x = 0;
x+=1;
return x;
}