把对象转换为字节序列的过程称为对象的序列化;
把字节序列恢复为对象的过程称为对象的反序列化。
使用友元函数
friend QDataStream& operator>> (QDataStream &in, CTest& data);
friend QDataStream& operator<< (QDataStream &out, const CTest& data);
QDataStream &operator>>(QDataStream &in, CTest &data)
{
in >> data.m_str >> data.m_name;
return in;
}
QDataStream &operator<<(QDataStream &out, const CTest &data)
{
out << data.m_str << data.m_name;
return out;
}
#if 1
CTest t; t.setData("abc", "xxx");
QFile fi("e:/a.txt");
fi.open(QIODevice::WriteOnly);
QDataStream out(&fi);
out << t;
fi.close();
#else
CTest t;
QFile fi("e:/a.txt");
fi.open(QIODevice::ReadOnly);
QDataStream in(&fi);
in >> t;
fi.close();
#endif
--------------------------------------------------------------------------
QBuffer序列化
QFont font1;
font1.setFamily("微软雅黑");
font1.setBold(true);
font1.setItalic(true);
font1.setPixelSize(24);
QBuffer buffer1;
buffer1.open(QIODevice::WriteOnly);
QDataStream out(&buffer1);
out << font1;
buffer1.close();
QByteArray array(buffer1.buffer());
QBuffer buffer2(&array);
buffer2.open(QIODevice::ReadOnly);
QDataStream in(&buffer2);
QFont font2;
in >> font2;