转载:http://www.cnblogs.com/cxjchen/p/3148582.html

转载:http://blog.csdn.net/hackbuteer1/article/details/7460019

.h文件

 #ifndef _SINGLETON_H_
#define _SINGLETON_H_ class Singleton{
public:
static Singleton* getInstance(); private:
Singleton();
//把复制构造函数和=操作符也设为私有,防止被复制
Singleton(const Singleton&);
Singleton& operator=(const Singleton&); static Singleton* instance;
}; #endif

.cpp文件

 #include "Singleton.h"

 Singleton::Singleton(){

 }

 Singleton::Singleton(const Singleton&){

 }

 Singleton& Singleton::operator=(const Singleton&){

 }

 //在此处初始化
Singleton* Singleton::instance = new Singleton();
Singleton* Singleton::getInstance(){
return instance;
}

main函数

#include "Singleton.h"
#include <stdio.h> int main(){
Singleton* singleton1 = Singleton::getInstance();
Singleton* singleton2 = Singleton::getInstance(); if (singleton1 == singleton2)
fprintf(stderr,"singleton1 = singleton2\n"); return ;
}
05-11 13:07