Qt中静态变量的使用方法
在头文件中声明静态变量:
static QQueue<QString> _q;
static StaticInstance Instance;
#ifndef STATICINSTANCE_H #define STATICINSTANCE_H #include <QObject> #include "systeminfo.h" class StaticInstance : public QObject { Q_OBJECT public: static QQueue<QString> _q; static StaticInstance Instance; void logError(const QString& err); signals: public slots: private: explicit StaticInstance(QObject *parent = nullptr); }; #endif // STATICINSTANCE_H
在cpp文件中也需要先写上静态变量声明或者赋值
StaticInstance StaticInstance::Instance;
QQueue<QString> StaticInstance::_q;
#include "staticinstance.h" #include "QString" #include "QDebug" #include "QQueue" StaticInstance StaticInstance::Instance; QQueue<QString> StaticInstance::_q; StaticInstance::StaticInstance(QObject *parent) : QObject(parent) { qDebug()<<"构造 Instance"; } void StaticInstance::logError(const QString &err) { StaticInstance::_q.enqueue(err); qDebug()<<StaticInstance::_q.dequeue(); }
特别说明:
在cpp文件的 最前面写上静态变量的信息,不然编译时就会报错。