C++ 使用 Qt 进行序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2570679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:57:03  来源:igfitidea点击:

Serialization with Qt

c++qtserializationqt4

提问by Narek

I am programming a GUI with Qt library. In my GUI I have a huge std::map.

我正在用 Qt 库编程一个 GUI。在我的 GUI 中,我有一个巨大的 std::map。

"MyType" is a class that has different kinds of fields.

“MyType”是一个具有不同类型字段的类。

I want to serialize the std::map. How can I do that? Does Qt provides us with neccesary features?

我想序列化 std::map。我怎样才能做到这一点?Qt 是否为我们提供了必要的功能?

回答by Narek

QDataStream handles a variety of C++ and Qt data types. The complete list is available at http://doc.qt.io/qt-4.8/datastreamformat.html. We can also add support for our own custom types by overloading the << and >> operators. Here's the definition of a custom data type that can be used with QDataStream:

QDataStream 处理各种 C++ 和 Qt 数据类型。完整列表可在http://doc.qt.io/qt-4.8/datastreamformat.html 获得。我们还可以通过重载 << 和 >> 运算符来添加对我们自己的自定义类型的支持。这是可以与 QDataStream 一起使用的自定义数据类型的定义:

class Painting
{
public:
    Painting() { myYear = 0; }
    Painting(const QString &title, const QString &artist, int year) {
        myTitle = title;
        myArtist = artist;
        myYear = year;
    }
    void setTitle(const QString &title) { myTitle = title; }
    QString title() const { return myTitle; }
    ...
private:
    QString myTitle;
    QString myArtist;
    int myYear;
};
QDataStream &operator<<(QDataStream &out, const Painting &painting);
QDataStream &operator>>(QDataStream &in, Painting &painting);

Here's how we would implement the << operator:

下面是我们如何实现 << 操作符:

QDataStream &operator<<(QDataStream &out, const Painting &painting)
{
    out << painting.title() << painting.artist()
        << quint32(painting.year());
    return out;
}

To output a Painting, we simply output two QStrings and a quint32. At the end of the function, we return the stream. This is a common C++ idiom that allows us to use a chain of << operators with an output stream. For example:

为了输出一幅画,我们只需输出两个 QStrings 和一个 quint32。在函数结束时,我们返回流。这是一个常见的 C++ 习惯用法,它允许我们在输出流中使用一连串 << 运算符。例如:

out << painting1 << painting2 << painting3;

出<<绘画1<<绘画2<<绘画3;

The implementation of operator>>() is similar to that of operator<<():

operator>>() 的实现与 operator<<() 类似:

QDataStream &operator>>(QDataStream &in, Painting &painting)
{
    QString title;
    QString artist;
    quint32 year;
    in >> title >> artist >> year;
    painting = Painting(title, artist, year);
    return in;
}

This is from: C++ GUI Programming with Qt 4 By Jasmin Blanchette, Mark Summerfield

这是来自:C++ GUI Programming with Qt 4 By Jasmin Blanchette, Mark Summerfield