我想理解为什么在此示例中使用引用函数?或在c ++中引用在函数中的重要性?

问题描述 投票:0回答:1

此代码,我想了解在原型中使用引用的必要性,如果不使用该引用会发生什么?

#include<iostream>
using namespace std; 
int &fun() 
{ 
    static int x = 10; 
    return x; 
} 
int main() 
{ 
    fun() ; 
    cout<<fun(); 
    return 0; 
} 
c++
1个回答
0
投票

这里没有“参考功能”。 &是返回类型的一部分,最好写成

int& fun() {...

该函数正在返回引用,以便您可以执行

int main() 
{ 
    fun() = 6;
    cout<<fun();   // will print 6 
    return 0; 
} 

注意,在大多数情况下,返回对函数局部变量的引用是错误的。在这里很好的原因是xstatic,这意味着:它将仅被初始化一次,并在函数调用之间保持其值。

例如,此函数将返回调用次数的计数器:

int count_me() {
    static int x = 0;
    x+=1;
    return x;
}
© www.soinside.com 2019 - 2024. All rights reserved.