c++/qt的数据序列化和反序列化

序列化以及反序列化的实现


 

struct Body

{
    double weight;
    double height;
};
//结构体
struct People
{
    int age;
    Body dBody;//结构体
    vector<QString> vecfamily;//vector
    //序列化
    friend QDataStream &operator<<(QDataStream& input,const People &iteam)
    {
        //vector 数据类型需要用vector<People>::fromStdVector 转一下
        //如果是QList则不需要直接插入
        QVector<QString> strvecfamily = QVector<QString>::fromStdVector(iteam.vecfamily);
        input << iteam.age << iteam.dBody.height << iteam.dBody.weight\
              << strvecfamily;
        return input;
    }
    //反序列化
    friend QDataStream &operator>>(QDataStream& output,People& iteam)
    {
        QVector<QString> vecfamily;
        output >> iteam.age >>iteam.dBody.height >> iteam.dBody.weight >> vecfamily;
        iteam.vecfamily = vecfamily.toStdVector();
        return output;
    }
};

数据的使用
People p1;
    p1.age = 12;
    p1.dBody.height = 150.8;
    p1.dBody.weight = 50;
    p1.vecfamily.push_back("sister");
    p1.vecfamily.push_back("mother");
    p1.vecfamily.push_back("father");
 
 
    QFile file("./stream.bat");
    if(!file.open(QIODevice::WriteOnly))
    {
        return ;
    }
    QDataStream input(&file);
    input << p1;
    file.close();
 
 
    People p2;
    QFile file1("./stream.bat");//.bat文件为二进制文件
    if(!file1.open(QIODevice::ReadOnly))
    {
        return ;
    }
    QDataStream output(&file1);
    output << p2;
    file.close();

output >> p2;
 
 
    qDebug()<<p2.age<<p2.dBody.height<<p2.dBody.weight\
           <<p2.vecfamily;//结果12 150.8 50 std::vector("sister", "mother", "father")

 

转载于:https://www.cnblogs.com/that-boy-done/p/10739097.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值