2012-01-25 2 views
4

Xcode를 사용하여 C++에서 싱글 톤 클래스를 만들려고합니다. 그것은 정말 기본적인 클래스이고 나는 이해하지 못하는 링커 에러를 얻습니다. any1 도와주세요 수 있습니까? 당신은을 정의 필요Xcode의 싱글 톤

Undefined symbols for architecture x86_64: 
    "Network::_instance", referenced from: 
     Network::instance() in Network.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

답변

4

: 여기

#include "Network.h" 

Network* Network::instance() { 
    if (!_instance) 
     _instance = new Network(); 
    return _instance; 
} 

컴파일러 오류입니다 : 여기
#ifndef _NETWORK_H_ 
#define _NETWORK_H_ 

#include <iostream> 
#include <list> 
#include "Module.h" 

using namespace std; 

/* 
* Assume only one network can run at a time 
* in the program. So make the class a singleton. 
*/ 
class Network { 
private: 
    static Network* _instance; 
    list<Module*> _network; 

public: 
    static Network* instance(); 
}; 

#endif 

가 IMPL 파일입니다 : 여기

클래스 헤더 파일입니다 구현 파일의 인스턴스 :

#include "Network.h" 

Network *Network::_instance; 

static Network *_instance; 선언은 어딘가에 Network::_instance이 있다고 말합니다. 실제로 존재하기 위해서는 어딘가에 단일 정의를 제공해야합니다.

+0

은 내가 헤더 파일을 가지고 파일을 구현하지 않는 경우이 인스턴스를 선언하는 방법을 궁금해 클래스는 내가 선언을 넣어야 경우, 하나 개의 파일에? – WindMemory

+0

@WindMemory 클래스 선언 외부의 소스 파일에 정의를 넣으십시오. –

+0

감사합니다. – WindMemory

6

어딘가에 Network::_instance의 실제 기억 장치를 선언해야합니다. 아마 impl. 파일.

시도하여 IMPL 파일에 추가 :

Network *Network::_instance=0; 
+0

+1 인스턴스 포인터를 0으로 설정하는 경우 초기화되지 않은 포인터를 확인하면 내 머리 속의 알람이 울립니다. –

+0

@VoDurden : 전역 데이터는 항상 0으로 초기화됩니다. –

+0

오! 고마워. 고마워. 그 점에 비추어 나는 또한 당신의 대답을 상향 투표하고 있습니다. –