在QDataStream中序列化类

时间:2014-03-20 01:25:40

标签: c++ qt

我正在尝试使用QVector<QPoint>保存3 QDataStream和int。

我重载operator<<(),但如果我尝试保存某些内容,则文件中不会显示任何内容。

我检查了QVector是否为空,但它不是。

所以这是带有operator<<save()函数的CloudData类:

CloudData.h

#include <QDataStream>
#include <QVector>
#include <QPoint>

class CloudData
{
public:
CloudData();

QVector<QPoint> getPolyVector() const;
QVector<QPoint> getPathPointVector() const;
QVector<QPoint> getSupPointVector() const;
int getRandSeed() const;

bool save(QString);
friend QDataStream& operator <<(QDataStream &dataStream, const CloudData &cd)
{
    dataStream << cd.getPolyVector() << cd.getPathPointVector()
               << cd.getSupPointVector() << cd.getRandSeed();
    return dataStream;
}

private:
QVector<QPoint> m_polyVector;
QVector<QPoint> m_pathPointVector;
QVector<QPoint> m_supPointVector;
int m_randSeed;
};

CloudData.cpp

#include "clouddata.h"
#include <QFile>

CloudData::CloudData()
{
}

void CloudData::setPolyVector(QVector<QPoint> pVec)
{
    m_polyVector = pVec;
}

void CloudData::setPathPointVector(QVector<QPoint> ppVec)
{
    m_pathPointVector = ppVec;
}

void CloudData::setSuppPointVector(QVector<QPoint> spVec)
{
    m_supPointVector = spVec;
}

void CloudData::setRandSeed(int randSeed)
{
    m_randSeed = randSeed;
}

bool CloudData::save(QString filename)
{
    QFile file(filename);
    if(!file.open(QIODevice::WriteOnly))
        return false;

    QDataStream out(&file);
    out.setVersion(QDataStream::Qt_4_8);

    out << this;
    file.close();
    return true;
}

最后,这是函数,它调用save()

void CloudWidget::saveCloudData()
{
    QString filename = QFileDialog::getSaveFileName(this,tr("Save cloud clutter data"),
                       "/Users/Admin/Downloads/", "Cloud Clutter Data (*.ccd)");
    m_cloudData.setPolyVector(m_polygon);
    m_cloudData.setPathPointVector(m_pathPointVector);
    m_cloudData.setSuppPointVector(m_supPointVector);
    m_cloudData.save(filename);
}

1 个答案:

答案 0 :(得分:0)

我相信这一行:

out << this;
save()方法中的

应为:

out << *this;

&lt;&lt;运算符处理对类的引用,而不是指向类的指针。

以下测试代码说明了这一点:

#include <QFile>
#include <QTextStream>
#include <QDebug>

class StreamTest
{
    public:
        StreamTest() { var1 = "var1"; var2 = "var2"; }
    QString var1;
    QString var2;

    friend QTextStream& operator <<(QTextStream &textStream, const StreamTest &st)
    {
        textStream << st.var1 << st.var2;
        return textStream;
    }

    void save(void)
    {
        QString str_1;
        QTextStream text_stream_1(&str_1);
        text_stream_1 << this;
        qDebug() << str_1;

        QString str_2;
        QTextStream text_stream_2(&str_2);
        text_stream_2 << *this;
        qDebug() << str_2;
    }
};

int main(int argc, char *argv[])
{
    StreamTest st;
    st.save();
}

运行代码会生成输出:

"0x7fff18070c10"
"var1var2"

打印指针值,而*打印所需的输出。