實施例:
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/TUTORIALS/C++Singleton.html
不,首先你需要一個很好的理由來使用單身人士,然後你需要另一個很好的理由,然後*然後*我們可以談論這樣做。 – delnan 2012-07-29 11:01:29
請避免單身。他們幾乎總是工作的錯誤工具。 [閱讀](http://jalf.dk/singleton) – jalf 2012-07-29 11:05:54
搜索之前問:http://stackoverflow.com/questions/1008019/c-singleton-design-pattern – 2012-07-29 11:13:14