2011-04-08 8 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

+2

@ user673769 : 예, §8.5/6은 모든 정적 객체가 최소 0으로 초기화되도록 보장합니다. 따라서 정의를'int Monitor :: count;'로 줄이면된다.하지만 정의가 필요하다. – ildjarn

2

정적 변수 count을 정의하지 않았습니다.

class Monitor 
{ 
    // ... 
}; 

int Monitor::count = 0 ; 

// ... 
+0

@ildjarn - 나는 프로그래밍 용어 : – Mahesh

+0

없음 걱정의 사용에 강타하고, 난 그냥 학자 연하입니다. ; -] – ildjarn