2012-02-26 10 views
1

私はいくつかのクラスのインターフェイスとして機能するクラスIDocumentを持っています。それはいくつかの抄録メソッド(virtual ... = 0)を持っています。私は、このようなすべてのサブクラスも直列化のためのオペレータ実装する必要がやりたいQtシリアライゼーション、非会員QDataStream&演算子<<

:、ここで説明オーバーロードされたストリーム演算子に加えて、あなたはQDataStreamにシリアライズしたい場合があります任意のQtのクラスを

をします

私は抽象演算子をどのように作成するのかは分かりませんが、それを非メンバーと定義するにはどうすればよいですか?

答えて

2

非メンバ演算子は、他の任意のフリー関数とほぼ同じような自由関数です。 operator<<上、QDataStreamについては、次のようになります。

#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

ありがとう:あなたのケースでは

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

、あなたはこのようなあなたのシリアル化を実装することができ(これはそれを行うためのひとつの方法である、他のものもあります)。同じパターンで読み込み演算子>>を実行します。 –

+0

n個の派生クラスを持つ、デシリアライズに関するアドバイス。すべての派生クラスでQ_DECLARE_METATYPEを使用し、QMetaTypeクラスでそれらを構築する必要がありますか? –

+0

はい、正しいアプローチ(QVariantがどこかに関わっている)のように聞こえます。 – Mat

関連する問題