C++程序设计之Qt自定义数据类型的序列化与反序列化

一、自定义数据类型

class Data_Record
{
public:
    Data_Record(int id = 0, QString name = "", int age = 0, QString addr = "");
    void display();
    friend QDataStream &operator<<(QDataStream &stream, const Data_Record &data); // 序列化
    friend QDataStream &operator>>(QDataStream &stream, Data_Record &data);       // 反序列化

private:
    int ID;
    QString name;
    int age;
    QString addr;
};

Data_Record::Data_Record(int ID, QString name, int age, QString addr)
{
    this->ID = ID;
    this->name = name;
    this->age = age;
    this->addr = addr;
}

void Data_Record::display()
{
    qDebug() << ID << name << age << addr;
}

QDataStream &operator<<(QDataStream &stream, const Data_Record &data)
{
    stream << data.ID << data.name << data.age << data.addr;
    return stream;
}

QDataStream &operator>>(QDataStream &stream, Data_Record &data)
{
    stream >> data.ID >> data.name >> data.age >> data.addr;

    return stream;
}

二、序列化

    QFile file1("QText.dat");
    if(!file1.open(QIODevice::WriteOnly | QIODevice::Text)) return;
    QDataStream out(&file1);
    out.setVersion(QDataStream::Qt_6_0);

    Data_Record data1(10000, "奥巴马", 18, "美利坚合众国华盛顿特区");

    out << data1;
    file1.close();

三、反序列化

    QFile file2("QText.dat");
    if(!file2.open(QIODevice::ReadOnly | QIODevice::Text)) return;
    QDataStream in(&file2);
    out.setVersion(QDataStream::Qt_6_0);

    Data_Record data2;
    in >> data2;
    data2.display();
    file2.close();

Leave a Reply

Your email address will not be published.