发现Qt下单例模式的实现有点不一样,记录一下。
这里定义的类是Connection.
声明:
#ifndef CONNECTION_H
#define CONNECTION_H
class Connection : public QObject
{
Q_OBJECT
public:
static Connection *getInstance()
{
if(conn==NULL){
conn = new Connection;
}
return conn;
}
private:
static Connection *conn;
explicit Connection(QObject *parent = 0);
};
#endif // CONNECTION_H
然后在构造函数上面初始化,如下:
Connection *Connection::conn=0;//方式也很特别,但是这句话漏了就不行
Connection::Connection(QObject *parent) : QObject(parent)
{
}
获取对象(这里不限制在Connection类中,即使在不同的类中,只要引用了头文件,都能共享一个对象):
Connection *conn=Connection::getInstance();
这样也就ok了。