可能重复:
What is an undefined reference/unresolved external symbol error and how do I fix it?
为什么我对以下代码有“未定义的Monitor::count
引用”错误?谢谢!
#include <iostream>
using namespace std;
class Monitor
{
static int count;
public:
void print() { cout << "incident function has been called " << count << " times" << endl; }
void incident() { cout << "function incident called" << endl; count++; }
};
void callMonitor()
{
static Monitor fooMonitor;
fooMonitor.incident();
fooMonitor.print();
}
int main()
{
for (int i = 0; i < 5; i++)
callMonitor();
return 1;
}
答案 0 :(得分:10)
因为你声明但是定义它。将以下内容放在.cpp文件中的一个(和仅一个)中:
int Monitor::count = 0;
答案 1 :(得分:2)
您尚未定义静态变量count
。
class Monitor
{
// ...
};
int Monitor::count = 0 ;
// ...