静态函数错误LNK2001:未解析的外部符号"private: static int B::s_nValue"

static function error LNK2001: unresolved external symbol "private: static int B::s_nValue"

本文关键字:static private int nValue 外部 LNK2001 错误 静态函数 符号      更新时间:2023-10-16
#pragma once
class B
{
private:
  static int s_nValue;
public:
  B();
  ~B();
  static int GetValue() { return s_nValue; }
  static void SetValue(int value){ s_nValue = value; }
};
int _tmain(int argc, _TCHAR* argv[])
{
  int i = 0;
  B::SetValue(5);
  std::cout << B::GetValue();
  cin>> i;
  return 0;
}

我正在尝试掌握静态函数的使用。在本例中,SetValue(( 和 GetValue(( 在类 B 中定义。 在 main 中调用它们时没有对象定义。这应该有效,但我收到一个未解决的外部符号错误 2001。预编译标头选项处于关闭状态。

如何摆脱此错误?

使用 MS Visual Studio 2012

静态

变量只声明而未定义,您应该在 cpp 文件中执行此操作:

int B::s_nValue = 0;