内:
#includeclass Singleton{public: static Singleton *GetInstance() { return m_pSingletom; } int function() { return 0; }private: static Singleton *m_pSingletom; // 构造私有函数 Singleton() { if (m_pSingletom == NULL) { m_pSingletom = new Singleton(); } }};Singleton *Singleton::m_pSingletom = 0;int main(int argc, const char * argv[]){ Singleton *single = Singleton::GetInstance(); int n = single->function(); printf("%d\n",n); std::cout << "Hello, World!\n"; return 0;}
外
.h#ifndef __SingletonDemo__Test__#define __SingletonDemo__Test__#includeclass Singleton{public: static Singleton *GetInstance(); int function();private: static Singleton *m_pSingleton;};#endif /* defined(__SingletonDemo__Test__) */
.cpp#include "Test.h"Singleton *Singleton::m_pSingleton = NULL;Singleton *Singleton::GetInstance(){ if (Singleton::m_pSingleton == NULL) { Singleton::m_pSingleton = new Singleton(); } return m_pSingleton;}int Singleton::function(){ return 9;}