简体   繁体   English

这段C ++代码如何工作?

[英]How does this piece of C++ code work?

I saw this below example in Geek For Geeks. 我在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.

But i am unable to map, how this value is arrived at. 但是我无法映射这个值是如何达到的。 Please help me as to how this piece of code works. 请帮助我了解这段代码的工作方式。

After some answers from experts, i got to know the value assigned to function is assigned to static variable x which is equivalent to fun()::x =30 经过专家的一些回答后,我知道分配给函数的值已分配给静态变量x,它等效于fun():: x = 30

Now, i tried a different piece of code.. where in i have 2 static variables inside the fun() and returning the second variable reference. 现在,我尝试了另一段代码..在其中,我在fun()中有2个静态变量,并返回第二个变量引用。 Still the answer is 30. Is is because when, fun() is assigned, it assigns the value 30 to all the variables inside fun()? 答案仍然是30。是因为在分配fun()时,它将值30分配给fun()内部的所有变量吗?

Second piece of code is 第二段代码是

#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;
}

fun returns a reference ( int& ) to the static variable x inside fun s scope. fun返回对fun范围内的static变量x的引用( int& )。 So essentially the statement fun() = 30 is fun::x = 30 . 因此从本质上说, fun() = 30的语句就是fun::x = 30 Note this is only safe because x is static . 注意,这仅是安全的,因为xstatic

function local static variables get initialized the first time into the function and persist until the end of the program. 函数局部静态变量首次在函数中初始化,并一直持续到程序结束。 So when you call 所以当你打电话

fun() = 30;

You return a reference to that variable and then assign 30 to it. 您返回对该变量的引用,然后为其分配30。 Since the variable is still alive it will keep that value. 由于变量仍然有效,它将保留该值。 Then 然后

cout << fun();

Is going to return the variable again. 将再次返回该变量。 Since it was already initialized it will not reset its value and it returns 30 as that is what it was set to in the preceding line. 由于它已经初始化,因此不会重置其值,它会返回30,因为这是在上一行中设置的值。

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

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