2012-02-26 35 views
1

我有一個類IDocument作爲一些類的接口。它有一些摘要方法(virtual ... = 0)。Qt序列化,非成員QDataStream&運算符<<

我願做這樣的所有子類也必須實現序列化操作:

除了這裏記錄的過載流運營商,任何的Qt類,你可能想要序列化操作QDataStream會有適當的流運營商宣佈爲非類的成員:

我甚至不知道如何做抽象運算符,但我如何定義它非成員?

回答

2

非會員運營商是一項免費功能,幾乎與任何其他免費功能一樣。對於QDataStream,在operator<<會是什麼樣子:

QDataStream& operator<<(QDataStream& ds, SomeType const& obj) 
{ 
    // do stuff to write obj to the stream 
    return ds; 
} 

在你的情況,你可以實現你的序列化這樣的(這是做的只是一種方式,也有其他人):

#include <QtCore> 

class Base { 
    public: 
     Base() {}; 
     virtual ~Base() {}; 
    public: 
     // This must be overriden by descendants to do 
     // the actual serialization I/O 
     virtual void serialize(QDataStream&) const = 0; 
}; 

class Derived: public Base { 
    QString member; 
    public: 
     Derived(QString const& str): member(str) {}; 
    public: 
     // Do all the necessary serialization for Derived in here 
     void serialize(QDataStream& ds) const { 
      ds << member; 
     } 
}; 

// This is the non-member operator<< function, valid for Base 
// and its derived types, that takes advantage of the virtual 
// serialize function. 
QDataStream& operator<<(QDataStream& ds, Base const& b) 
{ 
    b.serialize(ds); 
    return ds; 
} 

int main() 
{ 
    Derived d("hello"); 

    QFile file("file.out"); 
    file.open(QIODevice::WriteOnly); 
    QDataStream out(&file); 

    out << d; 
    return 0; 
} 
+0

感謝。我將以相同的模式執行讀操作符>>。 – 2012-02-26 15:06:05

+0

關於反序列化的任何建議,有n個派生類。我應該在所有派生類上使用Q_DECLARE_METATYPE並使用QMetaType類構造它們嗎? – 2012-02-26 20:37:06

+0

是的,這聽起來像是正確的方法(QVariant涉及某處)。 – Mat 2012-02-26 20:44:30