Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
重载QDataStream<<和>>运算符序列化和反序列化
#include <QDataStream>
#include <QString>
#include <QDebug>
struct Data1
{
bool isOk;
int value;
QString str;
};
struct Data2
{
bool isOk;
int value;
QString str;
// member funtion to serialize
Data2& operator>>(QDataStream& out)
{
out << isOk; // output to QDataStream
out << value;
out << str;
return *this;
}
// member funtion to deserialize
Data2& operator<<(QDataStream& in)
{
in >> isOk; // input from QDataStream
in >> value;
in >> str;
return *this;
}
};
// use non-member funtion to serialize
QDataStream& operator<<(QDataStream& out, const Data1& d)
{
out << d.isOk; // output to QDataStream
out << d.value;
out << d.str;
return out;
}
// use non-member funtion to deserialize
QDataStream& operator>>(QDataStream& in, Data1& d)
{
in >> d.isOk; // input from QDataStream
in >> d.value;
in >> d.str;
return in;
}
int main()
{
{
Data1 d;
d.isOk = true;
d.value = 123;
d.str = "456";
QByteArray ba;
{
QDataStream ds(&ba, QIODevice::WriteOnly);
ds << d;
qDebug() << "serialize" << d.isOk << d.value << d.str;
}
{
QDataStream ds(&ba, QIODevice::ReadOnly);
Data1 newD;
ds >> newD;
qDebug() << "deserialize" << newD.isOk << newD.value << newD.str;
}
}
{
Data2 d;
d.isOk = true;
d.value = 432;
d.str = "111";
QByteArray ba;
{
QDataStream ds(&ba, QIODevice::WriteOnly);
d >> ds;
qDebug() << "serialize" << d.isOk << d.value << d.str;
}
{
QDataStream ds(&ba, QIODevice::ReadOnly);
Data2 newD;
newD << ds;
qDebug() << "deserialize" << newD.isOk << newD.value << newD.str;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment