C++ Singleton class getInstance (as java)
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Can any one provide me a sample of Singleton in c++?
C++ Singleton design pattern
C++ different singleton implementations
我需要一些C++类中的单例例子,因为我从来没有写过这样的类。对于Java中的一个例子,我可以声明一个静态字段,它是私有的,它是在构造函数中初始化的,并且是一个静态的方法GET实例,并返回已经初始化的字段实例。
事先谢谢。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //.h class MyClass { public: static MyClass &getInstance(); private: MyClass(); }; //.cpp MyClass & getInstance() { static MyClass instance; return instance; } |
实例: logger.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #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.. } |
更多信息:
www.yolinux.com http:/ / / / C + +教程singleton.html