I don't know if it is possible to do this, but I have tried several ways and nothing 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With