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")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM