简体   繁体   English

为什么必须要有静电力?

[英]Why does static have to be there?

could anyone clarify this piece of code for me? 谁能为我澄清这段代码? I've done some research to understand references and static, but I still don't understand what does static do in this example. 我已经做了一些研究,以了解引用和静态信息,但是在此示例中,我仍然不了解静态信息的作用。 And why does it have to be there in the first place (If static is missing, the compiler gives warning and program could possibly crash, why?). 以及为什么它必须首先存在(如果缺少static,编译器会发出警告,程序可能会崩溃,为什么?)。

int & foo(int b)
{
    static int a = 7;


    a += b;
    return a;
}

int main() {

    int & x = foo(0);
    int & y = foo(1);
    cout << (x + y);

}

A static local variable will have a life-time of the full program. static局部变量将具有整个程序的生命周期。 A reference to it will never become invalid. 对其的引用将永远不会失效。

Otherwise, non-static local variables will "disappear" once they go out of scope (which happens when the function returns), and you can't have a reference to something that doesn't exist. 否则,非静态局部变量一旦超出范围(将在函数返回时发生),它们将“消失”,并且您将无法引用不存在的局部变量。

An important note about static local variables and their initialization: They are initialized only once , on the first call of the function. 有关static局部变量及其初始化的重要说明:在函数的第一次调用中,它们仅初始化一次 The variable will not be initialized on further calls, but will keep the last value it had. 该变量将不会在进一步调用时初始化,但会保留其具有的最后一个值。

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

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