更改对函数中静态变量的引用的值

Changing the value of a reference to a static variable in a function

本文关键字:变量 引用 静态 函数      更新时间:2023-10-16

请考虑以下C++代码片段:

#include <iostream>
using namespace std;
int &fun()
{
    static int a = 10;
    return a;
}
int main(int argc, char const *argv[])
{
    int &y = fun();
    y += 30;
    cout << fun();
    return 0;
}

输出:40

上面给出的代码片段的输出如何证明是合理的?

fun不是

函数指针,它是一个返回int&的空函数。具体来说,它返回对名为 astatic int的引用。

因此,您的程序所做的是:

int &y = fun(); // this is the first call to fun, so we initialize a.
                // it now has a value of 10, and we return a reference to it
                // so y is a reference to the static variable local to fun()
y += 30;        // y == 40
                // since y is a reference to "fun::a", a is now 40 too
cout << fun();  // a is static, so it will only get initialized once.
                // that first line is effectively a NOOP, so fun() just
                // returns a reference to it. which has a value of 40.

您没有使用函数指针,而只是将调用fun的结果存储在引用中。

a静态变量,您正在初始化对该变量的引用。在这种情况下,引用只是a的另一个名称,所以这就是为什么修改引用的值y,你也会修改值a,这是静态的,这意味着它的值在调用之间被保留。