2015-09-26 61 views
0

低於我代碼不爲comiling單例模式C++單例模式_實現與存儲器managenet

(錯誤LNK2019:解析外部符號 「私人:__thiscall辛格爾頓::辛格爾頓(無效)」(?? 0Singleton @@ AAE @ XZ)在函數「public:static class Singleton * __cdecl Singleton :: returnOneInstance(void)」(?returnOneInstance @ Singleton @@ SAPAV1 @ XZ)中引用)

任何人都可以幫忙嗎?我也想知道如何管理內存?謝謝

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 
#include <iterator> 

using namespace std; 

class Singleton 
{ 
private: 
    Singleton(); 
    Singleton(const Singleton& sing); 
    void operator=(const Singleton& sing); 
    static Singleton* singleton; 
    /*The 'instance' field holds the reference of the one and only instance. 
     It is stored in a static variable because its scope has to be the class itself and not a particular instance. 
    */ 
public: 
    static Singleton* returnOneInstance(); 
    void printme() const; 
}; 

Singleton* Singleton::singleton=NULL; 
Singleton* Singleton::returnOneInstance(){ 
    if (!singleton){ 
     singleton=new Singleton; 
    } 
    return singleton; 
}; 

void Singleton::printme()const { 
    cout << "I'm the Singleton" << endl; 
} 

int main() 

{ 
    Singleton* m=Singleton::returnOneInstance(); 
    m->printme(); 

    system("PAUSE"); 
    return 0; 
} 
+2

是,其中*是*了'辛格爾頓()'定義? –

+1

此外,不要忘記閱讀[什麼是單身人士如此糟糕?](http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons?rq=1) –

回答

0

基本上ctr尚未定義。我通過添加{}空主體來解決這個問題。在這種情況下,你只有一次對象實例,所以除非你想釋放單例的內存,否則沒有內存管理。在這種情況下,您可以提供銷燬該類並刪除保留的內存。

以下是你的代碼固定:

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 
#include <iterator> 

using namespace std; 

class Singleton 
{ 
private: 
    Singleton(){}; 
    Singleton(const Singleton& sing); 
    void operator=(const Singleton& sing); 
    static Singleton* singleton; 
    /*The 'instance' field holds the reference of the one and only instance. 
    It is stored in a static variable because its scope has to be the class itself and not a particular instance. 
    */ 
public: 
    static Singleton* returnOneInstance(); 
    void printme() const; 

}; 

Singleton* Singleton::singleton=NULL; 

Singleton* Singleton::returnOneInstance() 
{ 
    if (!singleton){ 
     singleton=new Singleton; 
    } 
    return singleton; 
}; 

void Singleton::printme()const { 
    cout << "I'm the Singleton" << endl; 
} 

int main() 

{ 
    Singleton* m=Singleton::returnOneInstance(); 
    m->printme(); 

    system("PAUSE"); 
    return 0; 
} 
+0

你是對,我編輯了答案以反映你的評論。謝謝。 – redobot