static function/variable

前端 未结 3 1641
太阳男子
太阳男子 2021-01-28 01:28

i just started programming in c++ this concept of static variable/function wasn\'t clear to me..why is this used and is there any other alternative of this!!!

相关标签:
3条回答
  • 2021-01-28 01:33

    static can be a little confusing because of its slightly different meaning depending upon where it is used.

    A static variable, declared globally, will only be visible in that source file.

    A static variable, declared locally, will keep its value over successive calls to that function (as in netrom's example)

    A static member variable does not belong to the class.

    A static function, declared in a class, can be used without declaring an instance of that class.

    0 讨论(0)
  • 2021-01-28 01:33

    why do we have to declare static in class and then assign the value outside the class!!!

    Because it's merely DECLARED in the class, it is not DEFINED.

    The class declaration is merely a description of the class, no memory is allocated until of object of that class is defined.

    If instances of the class can be defined in many modules, and the memory for allocated in many places, where do you put the one instance of the static data members? Remember, the class declaration can & will be included in many source files of the application.

    C++ has the "ODR" (which I insist should be the "1DR"): The "One Definition Rule". A data item can be DECLARED many times, but must be DEFINED exactly once. When you assign the value outside the class, the assignment part is actually irrelevant, it's the definition of the member that's important:

    class A
    {
        static int MyInt;    // Declaration
    };
    
    int A::MyInt;            // Definition
    
    0 讨论(0)
  • 2021-01-28 01:34

    The static keyword specifies that the life-time of the given the variable, function or class is application-wide. Like having a single instance.

    This example might illustrate it:

    #include <iostream>
    using namespace std;
    
    void test() {
      static int i = 123;
      if (i == 123) {
        i = 321;
      }
      cout << i << endl;
    }
    
    int main(int arg, char **argv) {
      test();
      test();
      return 0;
    }
    

    The output is:

    321

    321

    So "i" is only initialized the first time it is encountered, so to speak. But actually it's allocated at compile time for that function. Afterwards, it's just in the scope of the function test() as a variable, but it is static so changing it changes it in all future calls to test() as well.

    But I encourage you to read more about it here: http://www.cprogramming.com/tutorial/statickeyword.html

    0 讨论(0)
提交回复
热议问题