c++ - 具有 QObject 继承的单例 - Qt
问题描述
是否可以使用 QObject 继承创建单例类?添加 QObject 继承后出现编译错误。也许问题在于静态单例创建(应该是动态的)?这是我的方法
标题
#ifndef BLUETOOTHMANAGER_H
#define BLUETOOTHMANAGER_H
#include <QObject>
class BluetoothManager : public QObject
{
Q_OBJECT
public:
virtual ~BluetoothManager() {}
/// Static getter
static BluetoothManager & GetInstance()
{
return instance;
}
private:
/// static Bluetooth manager instance
static BluetoothManager instance;
explicit BluetoothManager(QObject * parent);
};
#endif // BLUETOOTHMANAGER_H
和cpp文件
#include "BluetoothManager.h"
/// singleton creation
BluetoothManager BluetoothManager::instance = BluetoothManager(static_cast<QObject*>(nullptr));
BluetoothManager::BluetoothManager(QObject * parent)
: QObject(parent)
{
}
在编译期间我有一个错误
../QtHealthApp/network/bluetooth/BluetoothManager.cpp:4:94: error: use of deleted function ‘BluetoothManager::BluetoothManager(const BluetoothManager&)’ BluetoothManager BluetoothManager::instance = BluetoothManager(static_cast<QObject*>(nullptr));
^ In file included from /opt/Qt5.12.LTS/5.12.6/gcc_64/include/QtCore/qnamespace.h:43:0,
from /opt/Qt5.12.LTS/5.12.6/gcc_64/include/QtCore/qobjectdefs.h:48,
from /opt/Qt5.12.LTS/5.12.6/gcc_64/include/QtCore/qobject.h:46,
from /opt/Qt5.12.LTS/5.12.6/gcc_64/include/QtCore/QObject:1,
from ../QtHealthApp/network/bluetooth/BluetoothManager.h:4,
from ../QtHealthApp/network/bluetooth/BluetoothManager.cpp:1: ../QtHealthApp/network/bluetooth/BluetoothManager.h:33:20: note: declared here
Q_DISABLE_COPY(BluetoothManager)
^ /opt/Qt5.12.LTS/5.12.6/gcc_64/include/QtCore/qglobal.h:372:5: note: in definition of macro ‘Q_DISABLE_COPY’
Class(const Class &) Q_DECL_EQ_DELETE;\
^
解决方案
推荐阅读
- javascript - 带有香草js的数组中匹配条目的grt数
- excel - 在设计模式下循环选择用户窗体控件
- reactjs - 如何在 useEffect() 中使用 React history.push() 路由到不同的页面
- java - ICEpdf 不呈现 PDF
- java - JsonPath / Java 如何在过滤中应用数据类型转换
- javascript - JavaScript 附加到 HTML
- powerpoint - MS Office openxml 获取PowerPoint幻灯片的幻灯片布局
- java - Google Cloud - Compute Engine,使用实例模板插入实例
- python - 恢复旧的 jupyter 笔记本
- shell - 如何从不同的目录运行多个 .sh 文件