/TEST测试类该类的友元函数 重载》 《
#ifndef TEST_H#define TEST_H#include <QString>typedef struct xx{ int x; int y;}XX;class Test{public: Test(); int age; QString name; XX aa; friend QDataStream& operator<<(QDataStream&,Test&); friend QDataStream& operator>>(QDataStream&,Test&);};#endif // TEST_H
//test的实现类,在友元函数负责将test对象的分解为基本数据类型,然后写入QDataStream流中。
#include "test.h"#include "qdatastream.h"Test::Test(){}QDataStream& operator <<(QDataStream& stream,Test& test){ qint32 tmp = test.age; qint32 x = test.aa.x; qint32 y = test.aa.y; stream<<tmp<<test.name<<x<<y; return stream;}QDataStream& operator >>(QDataStream& stream,Test& test){ qint32 tmp; qint32 x; qint32 y; XX xx; stream>>tmp>>test.name>>x>>y; xx.x = x; xx.y =y; test.age = tmp; test.aa = xx; return stream;}
主函数文件,测试是否写入成功,并成功读取磁盘文件。
Test test,out; test.age = 10; test.name="test"; test.aa.x = 5; test.aa.y = 6; QFile file("/d.dat"); file.open(QIODevice::ReadWrite); QDataStream stream(&file); stream<<test; file.close(); QFile file1("/d.dat"); file1.open(QIODevice::ReadWrite); QDataStream stream1(&file1); stream1>>out; file1.close();
我对对象序列化问题的理解是:将对象分解为平台能解析的基本数据类型,然后对基本数据类型进行写入操作。上例中的结构体XX为测试对象中含有结构体的序列化方法。对于对象中含有数组的情况,思路为:在保存对象磁盘文件中增加一个cout记录数组的元素个数(一维数组一个,多维数组记录多个),然后将数组的元素按行顺序写入到磁盘文件中,读取的时候则先读取数组的维数和元素个数,然后动态申请内存,将元素写入到内存中,将内存首地址赋值到对象的数组地址(即数组名)。对数组还没有进行测试。
这2天浪费时间都花在对平台的基本数据类型的修正中,比如使用QDataStream 将int直接写入肯定是不行,使用qint32可以。