可能重复:
Can any one provide me a sample of Singleton in c++?
C++ Singleton design pattern
C++ different singleton implementations
我需要一些C ++类中的Singleton示例,因为我从未编写过这样的类。 对于java中的一个例子,我可以声明一个私有的静态字段,它在构造函数中初始化,并且方法getInstance也是静态的,并返回已经初始化的字段实例。
提前致谢。
答案 0 :(得分:4)
//.h
class MyClass
{
public:
static MyClass &getInstance();
private:
MyClass();
};
//.cpp
MyClass & getInstance()
{
static MyClass instance;
return instance;
}
答案 1 :(得分: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..
}
更多信息: