开发者

How to share a static variable between C++ source files?

I don't know if it is possible to do this, but I have tried several ways and nothin开发者_开发百科g seems to work. Basically I need to access the same static member from several files which include the same class definition.

// Filename: S.h

class S {
public:
    static int foo;

    static void change(int new_foo) {
        foo = new_foo;
    }

};

int S::foo = 0;

Then in a class definition (other .cpp file) I have:

// Filename: A.h

#include "S.h"    

class A {
public:
    void do_something() {
        S::change(1);
    }
};

And in another file:

// Filename: program.cpp

#include "S.h"
#include "A.h"

int main (int argc, char * const argv[]) {
    A a = new A();
    S::change(2);        

    std::cout << S::foo << std::endl;

    a->do_something();

    std::cout << S::foo << std::endl;

}

Now, I would expect the second function call to change the S::foo to 1, but the output is still:

2

Is the A.h file creating a local copy of the static class?

Thank you Tommaso


This line:

int S::foo = 0;

needs to be in exactly one source file, not in the header. So move it from S.h to S.cpp.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜