2011-06-26 64 views
1

自從我用C++進行編程以來已經有一段時間了。我試圖實現一個單例類,但我得到一個無法解析的外部符號。你們能否指出解決這個問題?提前致謝!C++單例實現 - 靜態問題

class Singleton 
{ 
    Singleton(){} 
    Singleton(const Singleton & o){} 
    static Singleton * theInstance; 

public: 
    static Singleton getInstance() 
    { 
     if(!theInstance) 
      Singleton::theInstance = new Singleton(); 

     return * theInstance; 
    } 
}; 

錯誤:

錯誤3錯誤LNK1120:1周無法解析的外部

錯誤2錯誤LNK2001:解析外部符號"private: static class Singleton * Singleton::theInstance" ([email protected]@@[email protected])

+3

你可能也想回到'辛格爾頓&'從'的getInstance()'因爲否則會創建一個副本 – Cameron

+4

你也許不該不會使用單身。 –

+1

請參閱:http://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289 –

回答

9

你有宣佈Singleton::theInstance,但你沒有定義爲吧。加入它的定義在某些.cpp文件:

Singleton* Singleton::theInstance; 

(。此外,Singleton::getInstance應該返回Singleton&而非Singleton

+1

您希望在此處返回引用,而不是指向一個單一元素與指定工廠不同的指針b/c。一個工廠放棄了對象的所有權,而一個工廠卻沒有。這解釋得很好http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt – jdt141

4

您需要提供的theInstance類聲明的定義,在一個C++實現文件中:

Singleton *Singleton::theInstance; 
2

除了所有其他答案,喲ü可以只與私有成員做掉,並使用防靜電範圍函數變量:

static Singleton getInstance() 
{ 
    static Singleton * theInstance = new Singleton(); // only initialized once! 
    return *theInstance; 
} 
+2

爲什麼甚至有一個指針。只需創建一個靜態對象。還返回一個參考。 –

+0

@Tux:另外一個好主意:-) –