비회원 연산자는 다른 무료 함수와 거의 같은 무료 함수입니다. 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;
}
출처
2012-02-26 14:54:08
Mat
감사합니다. >> 같은 패턴으로 읽기 연산자 >>를 할 것입니다. –
n 개의 파생 된 클래스가있는 deserialize에 대한 조언. 파생 클래스 모두에서 Q_DECLARE_METATYPE을 사용해야하며 QMetaType 클래스로 구성해야합니까? –
예, 올바른 접근 방식 인 것 같습니다 (QVariant가 어딘가에 관련되어 있음). – Mat