2011-06-26 10 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(から'シングルトン& 'を返したい)'それ以外の場合は、あなたはおそらくshouldn – Cameron

+4

コピーが作成されますので、シングルトンを使用していない。 –

+1

参照:http://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289 –

答えて

9

あなたはSingleton::theInstanceを宣言したが、していますあなたはを定義していませんです。あなたは外のクラス宣言をtheInstanceの定義を提供する必要が

+1

シングルトンが典型的な工場と異なるポインタb/cではなく、ここで参照を返したいとします。ファクトリはオブジェクトの所有権を放棄しますが、シングルトンは所有しません。これはよく説明しています。http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt – jdt141

4

Singleton* Singleton::theInstance; 

(また、Singleton::getInstanceSingleton&ではなくSingletonを返す必要があります。):いくつかの.cppファイルにその定義を追加します。 C++実装ファイル:

Singleton *Singleton::theInstance; 
2

他のすべての回答の代わりに、yo uがちょうどプライベートメンバを廃止し、静的スコープ機能の変数を使用できます。

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

なぜポインタがあるのでしょうか。静的オブジェクトを作成するだけです。また、参照を返します。 –

+0

@Tux:いいアイデア:-) –

関連する問題