非メンバ演算子は、他の任意のフリー関数とほぼ同じような自由関数です。 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;
}
出典
2012-02-26 14:54:08
Mat
ありがとう:あなたのケースでは
、あなたはこのようなあなたのシリアル化を実装することができ(これはそれを行うためのひとつの方法である、他のものもあります)。同じパターンで読み込み演算子>>を実行します。 –
n個の派生クラスを持つ、デシリアライズに関するアドバイス。すべての派生クラスでQ_DECLARE_METATYPEを使用し、QMetaTypeクラスでそれらを構築する必要がありますか? –
はい、正しいアプローチ(QVariantがどこかに関わっている)のように聞こえます。 – Mat