【发布时间】:2015-09-01 12:11:48
【问题描述】:
我在 Geek For Geeks 中看到了以下示例。
#include<iostream>
using namespace std;
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
Answer is 30.
但我无法映射,这个值是如何得出的。请帮助我了解这段代码的工作原理。
经过一些专家的回答,我知道分配给函数的值是分配给静态变量 x 相当于 fun()::x =30
现在,我尝试了一段不同的代码。我在 fun() 中有 2 个静态变量并返回第二个变量引用。答案仍然是 30。是因为当 fun() 被赋值时,它会将值 30 赋给 fun() 中的所有变量?
第二段代码是
#include<iostream>
using namespace std;
int &fun()
{
static int x = 10;
static int y =20;
return y;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
【问题讨论】:
-
搜索和阅读references,以及了解
static局部变量的特别之处。
标签: c++ reference return-value