2

可能重复:
任何人都可以为我提供 C++ 中的 Singleton 示例吗?
C++ Singleton 设计模式
C++ 不同的单例实现

我需要一些 C++ 类中的 Singleton 示例,因为我从未编写过这样的类。对于java中的一个例子,我可以声明一个私有的静态字段,它在构造函数中初始化,一个方法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;
};

记录器.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/TUTORIALS/C++Singleton.html

于 2012-07-29T10:59:04.673 回答