The static keyword and its various uses in C++

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

    When you a declare a static variable at file scope, then that variable is only available in that particular file (technically, the *translation unit, but let's not complicate this too much). For example:

    a.cpp

    static int x = 7;
    
    void printax()
    {
        cout << "from a.cpp: x=" << x << endl;
    }
    

    b.cpp

    static int x = 9;
    
    void printbx()
    {
        cout << "from b.cpp: x=" << x << endl;
    }
    

    main.cpp:

    int main(int, char **)
    {
        printax(); // Will print 7
        printbx(); // Will print 9
    
        return 0;
    }
    

    For a local variable, static means that the variable will be zero-initialized and retain its value between calls:

    unsigned int powersoftwo()
    {
        static unsigned lastpow;
    
        if(lastpow == 0)
            lastpow = 1;
        else
            lastpow *= 2;
    
        return lastpow;
    }
    
    int main(int, char **)
    {
        for(int i = 0; i != 10; i++)
            cout << "2^" << i << " = " << powersoftwo() << endl;
    }
    

    For class variables, it means that there is only a single instance of that variable that is shared among all members of that class. Depending on permissions, the variable can be accessed from outside the class using its fully qualified name.

    class Test
    {
    private:
        static char *xxx;
    
    public:
        static int yyy;
    
    public:
        Test()
        {        
            cout << this << "The static class variable xxx is at address "
                 << static_cast(xxx) << endl;
            cout << this << "The static class variable yyy is at address "
                 << static_cast(&y) << endl;
        }
    };
    
    // Necessary for static class variables.
    char *Test::xxx = "I'm Triple X!";
    int Test::yyy = 0;
    
    int main(int, char **)
    {
        Test t1;
        Test t2;
    
        Test::yyy = 666;
    
        Test t3;
    };
    

    Marking a non-class function as static makes the function only accessible from that file and inaccessible from other files.

    a.cpp

    static void printfilename()
    { // this is the printfilename from a.cpp - 
      // it can't be accessed from any other file
        cout << "this is a.cpp" << endl;
    }
    

    b.cpp

    static void printfilename()
    { // this is the printfilename from b.cpp - 
      // it can't be accessed from any other file
        cout << "this is b.cpp" << endl;
    }
    

    For class member functions, marking them as static means that the function doesn't need to be called on a particular instance of an object (i.e. it doesn't have a this pointer).

    class Test
    {
    private:
        static int count;
    
    public:
        static int GetTestCount()
        {
            return count;
        };
    
        Test()
        {
            cout << this << "Created an instance of Test" << endl;
            count++;
        }
    
        ~Test()
        {
            cout << this << "Destroyed an instance of Test" << endl;
            count--;
        }
    };
    
    int Test::count = 0;
    
    int main(int, char **)
    {
        Test *arr[10] = { NULL };
    
        for(int i = 0; i != 10; i++)
            arr[i] = new Test();
    
        cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;
    
        // now, delete them all except the first and last!
        for(int i = 1; i != 9; i++)
            delete arr[i];        
    
        cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;
    
        delete arr[0];
    
        cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;
    
        delete arr[9];
    
        cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;
    
        return 0;
    }
    

提交回复
热议问题