【问题标题】:Serializing QHash with own Class?用自己的类序列化 QHash?
【发布时间】:2015-10-26 09:18:17
【问题描述】:

我有一个 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 的长度吗?

【问题讨论】:

    标签: c++ serialization qt5 qhash qdatastream


    【解决方案1】:

    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;
    }
    

    【讨论】:

      【解决方案2】:

      为 QHash 提供 operator&lt;&lt;operator&gt;&gt;; 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;
      }
      

      【讨论】:

        【解决方案3】:

        显然,有两种方法可以做事:

        1. operator&lt;&lt; 中,在保存 QHash 项之前,您应该保存 QHash::size
        2. operator&lt;&lt;的末尾保存一些无效的QString,例如空QString,在operator&gt;&gt;中,遇到这样的值就停止读取。

        【讨论】:

          猜你喜欢
          • 2013-02-04
          • 2011-07-20
          • 1970-01-01
          • 1970-01-01
          • 2013-11-17
          • 2018-06-18
          • 2019-04-08
          • 2012-04-12
          • 1970-01-01
          相关资源
          最近更新 更多