The static keyword and its various uses in C++

后端 未结 9 1798
自闭症患者
自闭症患者 2020-11-22 02:07

The keyword static is one which has several meanings in C++ that I find very confusing and I can never bend my mind around how its actually supposed to work.

9条回答
  •  佛祖请我去吃肉
    2020-11-22 02:44

    It's actually quite simple. If you declare a variable as static in the scope of a function, its value is preserved between successive calls to that function. So:

    int myFun()
    {
    static int i=5;
    i++;
    return i;
    }
    int main()
    {
    printf("%d", myFun());
    printf("%d", myFun());
    printf("%d", myFun());
    }
    

    will show 678 instead of 666, because it remembers the incremented value.

    As for the static members, they preserve their value across instances of the class. So the following code:

    struct A
    {
    static int a;
    };
    int main()
    {
    A first;
    A second;
    first.a = 3;
    second.a = 4;
    printf("%d", first.a);
    }
    

    will print 4, because first.a and second.a are essentially the same variable. As for the initialization, see this question.

提交回复
热议问题