版权声明:本文为博主原创文章,转载请注明 http://blog.csdn.net/u012741077 https://blog.csdn.net/u012741077/article/details/68945377
有一段时间不用c++了,突然用起来写了个类,编译居然报错了,怎么看都看不出问题出来=。=,不过最终还是找到原因所在了。
类中的静态变量必须初始化
错误代码如下:
# include <iostream>
using namespace std;
class MyClass
{
public:
static int count;
};
int main()
{
MyClass my;
my.count = 1;
return 0;
}
在编译的时候会报如下错误:
- “public: static int MyClass::count” (?count@MyClass@@2HA)
- fatal error LNK1120: 1 个无法解析的外部命令
所以必须加上下面代码:
//初始化静态变量
int MyClass::count = 0;
切记,切记!