用自己的类序列化QHash
Serializing QHash with own Class?
我有一个QHash<const QString id, MyClass>
,而MyClass只是一些带有getter和setter的QString quint8值的集合。MyClass也有一个覆盖的QDataStream &operator<<(QDataStream &ds, const MyClass &obj)
,在那里。
序列化使用:
typedef QHash<const QString, MyClass> MyClassHash;
//..
QDataStream &operator<<(QDataStream &ds, const MyClassHash &obj) {
QHashIterator<const QString, MyClass> i(obj);
while(i.hasNext())
{
i.next();
QString cKey = i.key();
ds << cKey << i.value();
}
return ds;
}
现在,我对另一个感到困惑:
QDataStream &operator>>(QDataStream &ds, MyClassHash &obj) {
obj.clear();
// ?
return ds;
}
我能知道这个序列化的QHash的长度吗?
QDataStream::status:
QDataStream &operator>>(QDataStream &ds, MyClassHash &obj) {
obj.clear(); // clear possible items
Myclass cMyCls;
while (!ds.status()) { // while not finished or corrupted
ds >> cKey >> cMyCls;
if (!cKey.isEmpty()) { // prohibits the last empty one
obj.insert(cKey, cMyCls);
}
}
return ds;
}
您不为QHash提供operator<<
和operator>>
;Qt已经为您提供了它们的实现。
只要您的键类型和值类型都可以使用QDataStream序列化,那么您就可以开始了:
class MyClass
{
int i;
friend QDataStream &operator<<(QDataStream &ds, const MyClass &c);
friend QDataStream &operator>>(QDataStream &ds, MyClass &c);
};
QDataStream &operator<<(QDataStream &ds, const MyClass &c)
{
ds << c.i;
return ds;
}
QDataStream &operator>>(QDataStream &ds, MyClass &c)
{
ds >> c.i;
return ds;
}
int main()
{
QHash<QString, MyClass> hash;
QDataStream ds;
// doesn't do anything useful, but it compiles, showing you
// that you don't need any custom streaming operators
// for QHash
ds << hash;
ds >> hash;
}
显然,有两种方法:
- 在
operator<<
保存QHash项目之前,你应该保存QHash::size - 在
operator<<
的末尾保存一些无效的QString,例如空的QString,并且在operator>>
中,当满足该值时停止读取。
相关文章:
- 如何在C++中序列化结构数据
- 序列化,没有库的整数,得到奇怪的结果
- 如何知道QDataStream不能反序列化某些内容
- 如何使用Python从C++中读取谷物序列化数据
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 带有Protobuf序列化的C++Hazelcast:字符串不是UTF-8格式的
- 自定义对象的dlib序列化在gcc中失败
- C++boost序列化多态性问题
- 增强基于 XML class_id的反序列化
- 提升反序列化对象具有 nan 或 -nan 值
- 在 cpp 中的平面缓冲区中序列化对象
- 每次进行继承时都需要提升::序列化::base_object吗?
- 如何在 c++ 非托管代码中反序列化 byte[] 的 json 字符串?
- 提升序列化 1:73 的向后兼容性问题
- 将 boost 序列化对象的 asio::streambuf 表示转换为 Beast 的 DynamicBody req.body()
- 为什么 nlohmann/json 序列化 "null" 而不是在 double 上"0"?
- 如何反序列化数组?
- 如何使用提升序列化?
- 序列化多晶型接口
- 用自己的类序列化QHash