简体   繁体   English

任何人都可以解释输出?

[英]can anyone explain the output?

Can anyone explain the output? 任何人都可以解释输出吗?

#include<iostream>

using namespace std;  

int &fun(){   
  static int x = 10;   
  return x;   
} 

int main(){         
  fun() = 30;
  cout << fun();          
  return 0;         
}

output is 30 输出是30

That's how static locals work - they persist the value between the function calls. 这就是静态本地工作的方式 - 它们在函数调用之间保持值。 Basically fun() has a static local and returns a reference to it, the effect is roughly the same as you would have with a global variable. 基本上fun()有一个静态局部并返回对它的引用,效果与全局变量的效果大致相同。

You return the static by reference, so when you do fun() = 30 you change it. 您可以通过引用返回静态,因此当您执行fun() = 30您可以更改它。

It's pretty clear, no? 很清楚,不是吗?

Basically, foo() returns a reference to x . 基本上, foo()返回对x引用

When you call fun() a static variable is created and you return the reference to it. 当你调用fun()会创建一个静态变量并返回对它的引用。 Basically, because of the static , the variable is not destroyed even if you exit the scope of the function. 基本上,由于static ,即使退出函数的范围,变量也不会被销毁。 You affect the reference with 30 and then recalling the function you get 30 (the x at the second call is exactly the same at the first call). 您使用30影响参考,然后调用您获得的函数30(第二次调用时的x在第一次调用时完全相同)。 Basically the static works like a global variable in this case. 基本上静态就像这种情况下的全局变量一样。

AS fun is the reference to the function so when you write this line fun() = 30; AS fun是对函数的引用所以当你写这行时fun() = 30; it stores 30 in its return value ie x , that is why you are getting the output as 30. 它将30存储在其返回值即x ,这就是为什么输出为30的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM