C++程序设计之Qt标准容器类的序列化与反序列化

C++程序设计,Qt中使用QDataStream类实现对象序列化与反序列化。Boost准标准库提供对标准模板库的序列化与反序列化,Qt暂时不提供此功能,需要我们自己写代码实现。具体过程如下:

一、序列化

QDataStream &operator<<(QDataStream &stream, const Data &data)
{
    int count = data.vec.size();
    stream << count;
    for(int i=0; i<count; i++)
    {
        stream << data.vec.at(i);
    }
    return stream;
}

二、反序列化

QDataStream &operator>>(QDataStream &stream, Data &data)
{
    int count;
    stream >> count;
    data.vec.resize(count);
    QString str;
    for(int i=0; i<count; i++)
    {
        stream >> str;
        data.vec[i] = str;
    }
    return stream;
}

三、代码示例

#include <QtCore>

struct Data
{
    QVector<QString> vec;
};

// 序列化
QDataStream &operator<<(QDataStream &stream, const Data &data)
{
    int count = data.vec.size();
    stream << count;
    for(int i=0; i<count; i++)
    {
        stream << data.vec.at(i);
    }
    return stream;
}

// 反序列化
QDataStream &operator>>(QDataStream &stream, Data &data)
{
    int count;
    stream >> count;
    data.vec.resize(count);
    QString str;
    for(int i=0; i<count; i++)
    {
        stream >> str;
        data.vec[i] = str;
    }
    return stream;
}

int main(void)
{
    QByteArray ba;

    QDataStream out(&ba, QIODevice::WriteOnly);
    Data data1;
    data1.vec = {"bj", "sh", "xa", "nj"};
    out << data1;

    QDataStream in(&ba, QIODevice::ReadOnly);
    Data data2;
    in >> data2;
    qDebug() << data2.vec;

    return 0;
}

Leave a Reply

Your email address will not be published.