用自己的类序列化QHash

Serializing QHash with own Class?

本文关键字:QHash 序列化 自己的      更新时间:2023-10-16

我有一个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;
}

显然,有两种方法:

  1. operator<<保存QHash项目之前,你应该保存QHash::size
  2. operator<<的末尾保存一些无效的QString,例如空的QString,并且在operator>>中,当满足该值时停止读取。