我是 C++ 新手,我正在尝试学习 static 关键字的不同用途,我读到其中之一是在类中定义一个静态变量并使用范围运算符调用它。我尝试使用它,但 Visual Studio 2012 产生链接错误。我的代码是:
class Vehicle
{
public:
Vehicle(){};
~Vehicle(){};
static int temp;
};
int _tmain(int argc, _TCHAR* argv[])
{
Vehicle::temp=100;
std::cout << Vehicle::temp << std::endl;
system("Pause");
return 0;
}
错误是:
1>LearningC++.obj : error LNK2001: unresolved external symbol "public: static int Vehicle::temp" (?temp@Vehicle@@2HA)
1>c:\users\avraam\documents\visual studio 2012\Projects\LearningC++\Debug\LearningC++.exe : 致命错误 LNK1120: 1 unresolved externals
什么可能导致这个问题?
Edit1(为了更清楚):
我的问题是如何访问在类中声明的静态变量?这可能不使用成员函数吗?