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

2024-05-02

我在 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;
}

fun返回一个引用(int&)到static多变的x inside fun的范围。所以本质上是这样的声明fun() = 30 is fun::x = 30。请注意,这只是安全的,因为x is static.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

这段C++代码是如何工作的? 的相关文章