Static variables in instance methods

前端 未结 5 1651

Let\'s say I have this program:

class Foo {
 public:
    unsigned int bar () {
        static unsigned int counter = 0;
        return counter++;
    }
};

int m         


        
5条回答
  •  别那么骄傲
    2021-02-14 03:39

    Your example was a couple lines away from being something you could compile and test:

    #include 
    using namespace std;
    class Foo {
     public:
        unsigned int bar () {
            static unsigned int counter = 0;
            return counter++;
        }
    };
    
    int main ()
    {
        Foo a;
        Foo b;
    
        for (int i=0; i < 10; i++)
          cout<

    The output looks like this:

    0. 1 / 0
    1. 3 / 2
    2. 5 / 4
    3. 7 / 6
    4. 9 / 8
    5. 11 / 10
    6. 13 / 12
    7. 15 / 14
    8. 17 / 16
    9. 19 / 18
    

    So yes, the counter is shared across all instances.

提交回复
热议问题