2

重複の可能性:
C ++のシングルトンのサンプルを提供してくれる人はいますか?
C++シングルトンデザインパターン
C++のさまざまなシングルトン実装

私はそのようなクラスを書いたことがないので、c++クラスのシングルトンの例が必要です。Javaの例では、プライベートであり、コンストラクターで初期化されるda静的フィールドと、これも静的で、すでに初期化されているフィールドインスタンスを返すメソッドgetInstanceを宣言できます。

前もって感謝します。

4

2 に答える 2

4
//.h
class MyClass
{
public:
    static MyClass &getInstance();

private:
    MyClass();
};

//.cpp
MyClass & getInstance()
{ 
    static MyClass instance;
    return instance;
}
于 2012-07-29T10:57:50.783 に答える
2

例:
logger.h:

#include <string>

class Logger{
public:
   static Logger* Instance();
   bool openLogFile(std::string logFile);
   void writeToLogFile();
   bool closeLogFile();

private:
   Logger(){};  // Private so that it can  not be called
   Logger(Logger const&){};             // copy constructor is private
   Logger& operator=(Logger const&){};  // assignment operator is private
   static Logger* m_pInstance;
};

logger.c:

#include "logger.h"

// Global static pointer used to ensure a single instance of the class.
Logger* Logger::m_pInstance = NULL; 

/** This function is called to create an instance of the class.
    Calling the constructor publicly is not allowed. The constructor
    is private and is only called by this Instance function.
*/

Logger* Logger::Instance()
{
   if (!m_pInstance)   // Only allow one instance of class to be generated.
      m_pInstance = new Logger;

   return m_pInstance;
}

bool Logger::openLogFile(std::string _logFile)
{
    //Your code..
}

詳細情報:

http://www.yolinux.com/tokyoS/C++Singleton.html

于 2012-07-29T10:59:04.673 に答える