可以在一个头文件中定义一个宏:
#ifndef DECLARE_SINGLETON
#define DECLARE_SINGLETON(T)\
public:\
static T * singleton();
#endif
#ifndef DEFINE_SINGLETON
#define DEFINE_SINGLETON(T,s) static T* s=NULL;\
T * T::singleton(){ if(s==NULL){s=new T; return s;} return s; }
#endif
在需要单例的类中,单例声明DECLARE_SINGLETON(T)
单例实现 DEFINE_SINGLETON(T,s)