这段C ++代码如何工作? [英] How does this piece of C++ code work?

查看:48
本文介绍了这段C ++代码如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Geek For Geeks中看到了以下示例.

I saw this below example in 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.

经过专家的解答,我知道分配给函数的值已分配给静态变量x,它等效于fun():: x = 30

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

现在,我尝试了另一段代码..在其中,我在fun()中有2个静态变量,并返回第二个变量引用.答案仍然是30.是因为当分配fun()时,它会将值30分配给fun()内部的所有变量吗?

Now, i tried a different piece of code.. where in i have 2 static variables inside the fun() and returning the second variable reference. Still the answer is 30. Is is because when, fun() is assigned, it assigns the value 30 to all the variables inside 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;
}

推荐答案

fun 返回对 static 变量的引用( int& )在 fun 范围内的 x .因此,语句 fun()= 30 本质上是 fun :: x = 30 .请注意,这只是安全的,因为 x static .

fun returns a reference (int&) to the static variable x inside funs scope. So essentially the statement fun() = 30 is fun::x = 30. Note this is only safe because x is static.

这篇关于这段C ++代码如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆