The static keyword and its various uses in C++

后端 未结 9 1792
自闭症患者
自闭症患者 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:53

    I'm not a C programmer so I can't give you information on the uses of static in a C program properly, but when it comes to Object Oriented programming static basically declares a variable, or a function or a class to be the same throughout the life of the program. Take for example.

    class A
    {
    public:
        A();
        ~A();
        void somePublicMethod();
    private:
        void somePrivateMethod();
    };
    

    When you instantiate this class in your Main you do something like this.

    int main()
    {
       A a1;
       //do something on a1
       A a2;
       //do something on a2
    }
    

    These two class instances are completely different from each other and operate independently from one another. But if you were to recreate the class A like this.

    class A
    {
    public:
        A();
        ~A();
        void somePublicMethod();
        static int x;
    private:
        void somePrivateMethod();
    };
    

    Lets go back to the main again.

    int main()
    {
       A a1;
       a1.x = 1;
       //do something on a1
       A a2;
       a2.x++;
       //do something on a2
    }
    

    Then a1 and a2 would share the same copy of int x whereby any operations on x in a1 would directly influence the operations of x in a2. So if I was to do this

    int main()
    {
       A a1;
       a1.x = 1;
       //do something on a1
       cout << a1.x << endl; //this would be 1
       A a2;
       a2.x++;
       cout << a2.x << endl; //this would be 2 
       //do something on a2
    }
    

    Both instances of the class A share static variables and functions. Hope this answers your question. My limited knowledge of C allows me to say that defining a function or variable as static means it is only visible to the file that the function or variable is defined as static in. But this would be better answered by a C guy and not me. C++ allows both C and C++ ways of declaring your variables as static because its completely backwards compatible with C.

提交回复
热议问题