转载:http://www.cnblogs.com/cxjchen/p/3148582.html
转载:http://blog.csdn.net/hackbuteer1/article/details/7460019
.h文件
1 #ifndef _SINGLETON_H_ 2 #define _SINGLETON_H_ 3 4 5 class Singleton{ 6 public: 7 static Singleton* getInstance(); 8 9 private: 10 Singleton(); 11 //把复制构造函数和=操作符也设为私有,防止被复制 12 Singleton(const Singleton&); 13 Singleton& operator=(const Singleton&); 14 15 static Singleton* instance; 16 }; 17 18 #endif
.cpp文件
1 #include "Singleton.h" 2 3 4 Singleton::Singleton(){ 5 6 } 7 8 9 Singleton::Singleton(const Singleton&){ 10 11 } 12 13 14 Singleton& Singleton::operator=(const Singleton&){ 15 16 } 17 18 19 //在此处初始化 20 Singleton* Singleton::instance = new Singleton(); 21 Singleton* Singleton::getInstance(){ 22 return instance; 23 }
main函数
#include "Singleton.h" #include <stdio.h> int main(){ Singleton* singleton1 = Singleton::getInstance(); Singleton* singleton2 = Singleton::getInstance(); if (singleton1 == singleton2) fprintf(stderr,"singleton1 = singleton2 "); return 0; }