可能重複:
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? – user673769 2011-04-08 21:53:13
@ user673769:是的,§8.5/ 6保證所有靜態對象的最小零初始化。因此,如果需要,可以將定義縮短爲「int Monitor :: count;',但定義是必需的。 – ildjarn 2011-04-08 22:00:57