2011-04-08 181 views
0

可能重複:
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; 
} 

回答

9

因爲你聲明,但不定義它。把下面的在你的.cpp文件之一(和一個):

int Monitor::count = 0; 
+0

是不是靜態變量默認初始化爲0? – user673769 2011-04-08 21:53:13

+2

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

2

您尚未定義靜態變量count

class Monitor 
{ 
    // ... 
}; 

int Monitor::count = 0 ; 

// ... 
+0

@ildjarn - 我在編程術語:) – Mahesh 2011-04-08 21:49:03

+0

沒有後顧之憂的使用來襲,我只是迂腐。 ; - ] – ildjarn 2011-04-08 21:49:29