2009-07-14 11 views
1
가능한 중복

: 이제
Undefined reference - C++ linker error정의되지 않은 참조 오류 메시지 - C++

, 나는 'GlobalClass :: s_instance'에 "정의되지 않은 참조 오류 메시지를 받고 있어요, 그리고 'GlobalClass :: 각각이 문에 예(), :

GlobalClass *GlobalClass::s_instance = 0; 

GlobalClass::instance()->set_value(myAddress); \\ <== undefined reference  
std::cout << "====>address is is " << GlobalClass::instance()->get_value() 

어떤 아이디어를 코드는 다음과 같습니다

================================

#ifndef GLOBALCLASS_H_ 
#define GLOBALCLASS_H_ 

#include <string> 
class GlobalClass { 

public: 

    std::string get_value(); 

    void set_value(std::string); 

    static GlobalClass *instance(); 

    static GlobalClass *s_instance; 

private: 

    std::string m_value; 
}; 

#endif /* GLOBALCLASS_H_ */ 

=========================================== ====

#include <string> 
#include "GlobalClass.h" 



/* 
GlobalClass(int v = 0) 
{ 
m_value = v; 
} 
*/ 

    static GlobalClass *s_instance; 

    std::string GlobalClass::get_value() 
    { 
     return m_value; 
    } 

    void GlobalClass::set_value(std::string v) 
    { 
     m_value = v; 
    } 

    static GlobalClass *instance() { 
     if (!s_instance) 
       s_instance = new GlobalClass; 
     return s_instance; 
    } 

======================================= 당신의 CPP 파일에서 ====================

#include <iostream> 
#include "GlobalClass.h" 

using namespace std; 

int main() { 

    GlobalClass::s_instance = 0; \\ <== undefined reference 


    std::string myAddress = "abc"; 
    GlobalClass::instance()->set_value(myAddress); \\ <== undefined reference 

    std::cout << "====>address is is " << GlobalClass::instance()->get_value() 
    \\ <== undefined reference 

       << std::endl; 
    return 0; 

}

+0

정확한 복제본 : http://stackoverflow.com/questions/1122938/undefined-reference-c-linker-error –

+0

다른 오류가 있다는 것을 알고 있지만 다른 질문과 같은 문제이므로 거기에 답변을 게시하고 이것을 닫으려는 투표. –

+1

네, 문제 없습니다. 나는 그걸로 무엇을해야할지 모르겠다. –

답변

2

Alex Black의 답변에 더하여 GlobalClass :: instance() 함수에는 구현이 없다는 불평이 있습니다. 어떤 그렇지 않습니다 :

static GlobalClass *instance() { 
     if (!s_instance) 
       s_instance = new GlobalClass; 
     return s_instance; 
    } 

은 정말이되어야한다 :

GlobalClass *GlobalClass::instance() { 
      if (!s_instance) 
        s_instance = new GlobalClass; 
      return s_instance; 
     } 

가 정적 경우에도 여전히 멤버 함수임을 잊지 마세요!

+0

아마도 그랬을 것입니다. 쳇! –

2

, m ove "Global :: s_instance = 0;"main() 외부에 정적으로 접두사를 붙입니다.

static Global::s_instance = 0; 
int main() 
{ 
... 
}