tun*_*nuz 3 c++ static scope class file
我不知道是否有可能做到这一点,但我尝试了几种方法似乎没有任何效果.基本上我需要从几个包含相同类定义的文件中访问相同的静态成员.
// Filename: S.h
class S {
public:
static int foo;
static void change(int new_foo) {
foo = new_foo;
}
};
int S::foo = 0;
Run Code Online (Sandbox Code Playgroud)
然后在类定义(其他.cpp文件)中我有:
// Filename: A.h
#include "S.h"
class A {
public:
void do_something() {
S::change(1);
}
};
Run Code Online (Sandbox Code Playgroud)
在另一个文件中:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
现在,我希望第二个函数调用将S :: foo更改为1,但输出仍然是:
2
Run Code Online (Sandbox Code Playgroud)
Ah文件是否创建了静态类的本地副本?
谢谢Tommaso
int*_*jay 13
这一行:
int S::foo = 0;
Run Code Online (Sandbox Code Playgroud)
需要只在一个源文件中,而不是在标题中.所以把它从那里S.h移到S.cpp.