将流运算符添加到 Qt 对象

Add stream operators to Qt object

本文关键字:Qt 对象 添加 运算符      更新时间:2023-10-16

是否可以将流运算符添加到现有的Qt对象中?我尝试在此示例代码中执行此操作(QFileSystemWatcher),最后一行不编译。编译LineUser示例。

用于注册流运算符的文档。

#include <QtCore>
class LineUser {
public:
int uId;
QString passwd;
qint8 statusType;
};
Q_DECLARE_METATYPE(LineUser)
QDataStream &operator<<(QDataStream &out, const LineUser &myObj) {
out<<myObj.uId<<myObj.passwd<<myObj.statusType;
return out;
}
QDataStream &operator>>(QDataStream &in, LineUser &myObj) {
in>>myObj.uId>>myObj.passwd>>myObj.statusType;
return in;
}
QDataStream &operator<<(QDataStream &out, const QFileSystemWatcher &myObj) {
return out;
}
QDataStream &operator>>(QDataStream &in, QFileSystemWatcher &myObj) {
return in;
}
int main() {
qRegisterMetaTypeStreamOperators<LineUser>("LineUser");
qRegisterMetaTypeStreamOperators<QFileSystemWatcher>("QFileSystemWatcher");
}

编译器消息很长,这里有一些错误:

error: use of deleted function ‘QFileSystemWatcher::QFileSystemWatcher(const QFileSystemWatcher&)’
return new (where) T(*static_cast<const T*>(t));
note: ‘QFileSystemWatcher::QFileSystemWatcher(const QFileSystemWatcher&)’ is implicitly deleted because the default definition would be ill-formed:
class Q_CORE_EXPORT QFileSystemWatcher : public QObject error: ‘QObject::QObject(const QObject&)’ is private
Q_DISABLE_COPY(QObject) 
error: within this context  class Q_CORE_EXPORT QFileSystemWatcher : public QObject note: declared here
Q_DISABLE_COPY(QObject)

从这里:

具有公共默认构造函数

(公共构造函数)的任何类或结构 可以注册复制构造函数和公共析构函数。

从这里开始:

QObject既没有复制构造函数,也没有赋值运算符。 这是设计使然。

因此,显然,存在一个设计限制,阻止QObject派生注册为元类型(这也是有道理的,因为它不是必需的,因为默认情况下会为它们生成元信息),因此qRegisterMetaTypeStreamOperators也是行不通的。

不过,它应该适用于QFileSystemWatcher *