这一定很琐碎,但我找不到:
struct Test {
static int n;
void Save(int val) {
Test::n = val;
}
};
int main() {
Test t;
t.Save(2);
return 0;
}
为什么第 4 行有对 Test::n
的 undefined reference ?
最佳答案
你需要定义静态:
struct Test {
static int n;
void Save(int val) {
Test::n = val;
}
};
int Test::n = 0;
请注意,定义必须出现在实现文件中,而不是标题中,否则会出现多重定义错误。
关于c++ - 通过非静态方法访问静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10623037/