c++ - 通过非静态方法访问静态成员

标签 c++

这一定很琐碎,但我找不到:

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/

相关文章:

c++ - Qt C++ : Linking multiple instances of a QPushButton subclass using Signals/Slots

c++ - 导入C++模块,如果失败: import Python version?

c++ - Gmock 参数化测试运行两次

c++ - std::move 是否会使指向 unique_ptr 所拥有的对象的原始指针无效?

c++ - 类型检查 std::map 的键和/或 boost::any 类型的值?

c++ - 从 libpurple(支持 Pidgin 的 IM 库)检索另一个用户的状态

c++ - 修改task.json以编译多个c++文件

c++ - 函数 v8::Value::IsInt32 没有地址

c++ - 如何将文件添加到 Codelite 中的现有项目?

c++ - 进程内函数调用的开销