返回对整数的引用时的 C++ 代码

标签 c++ reference

我尝试了以下代码:

int& fun()
{
    static int y = 20;
    //y = 40;
    return y;
}
int main()
{
    fun() = 30;
    cout << fun() <<endl;
    return 0;
}

如果 y = 40 行未注释,则 main 的输出为 40。为什么 y 的值在 main() 中分配给 30 时没有改变?

最佳答案

变量y函数 func() 的 static 存储时间:

3.7.1/1: All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program

3.7.1/3: The keyword static can be used to declare a local variable with static storage duration.

此类变量的初始化只发生一次。这意味着您第一次使用 y它的值为 20,之后它会保留你存储在那里的值。

情况一:赋值被注释掉:

声明fun() = 30;将在 y 中存储 30。 cout << fun()将在不使用 fun() 的情况下使用对 y 的引用改变它,所以它会显示 30。

情况二:赋值被激活:

声明fun() = 30;将在 y 中存储 30。 cout << fun()将使用对 y 的引用,但 fun()将首先将其设置为 40,因此将显示 40。

关于返回对整数的引用时的 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34711966/

相关文章:

javascript - 内联JS不以html形式调用

javascript - 通过 Javascript/HTML 生成随机链接

c++ - 这个语法是什么意思, `class template <class R, class ...Args> class name<R(Args...)>`

c++ - 查找变量声明的简便方法

c++ - 在 C++ 中检查是否存在时出错

c++ - ACM : Web Navigation

arrays - 一行创建一个对 n 个空字符串数组的 perl 数组引用

c++ - 引用是否占用堆栈空间

c++ - 如何读取包含多个根元素的 JSON 文件?

c++返回局部变量的const引用