#ifndef A_H #define A_H #include <QObject> class A : public QObject{ Q_OBJECT public: static A* instance(){ static A a; return &a; } public: void emitSignalA(){ signalA(); } signals: void signalA(); }; #define PA (A::instance()) #endif // A_H
直接在.h中定义了宏PA,返回类A的单例对象指针。把宏定义到.h文件中可以供别的程序调用。
class CSingleton { private: CSingleton() { } static CSingleton *p; public: static CSingleton* getInstance() { return p; } }; CSingleton* CSingleton::p = new CSingleton();
//总结:利用静态变量和私有化构造函数的特性来实现单例模式。搞一个静态的自身类指针,然后把构造函数私有化,这样new的时候就只能让本类中的成员调用,然后不择手段在类内部new出这个对象,并提供一种方法供外部得到这个对象的地址。