c++ - Qt 序列化,非成员 QDataStream & operator<<

标签 c++ qt serialization

我有一个 IDocument 类,它用作某些类的接口(interface)。它有一些抽象方法(virtual ... = 0)。

我想这样做,所有子类也必须实现一个序列化运算符:

In addition to the overloaded stream operators documented here, any Qt classes that you might want to serialize to a QDataStream will have appropriate stream operators declared as non-member of the class:

我什至不确定如何创建抽象运算符,但如何定义它为非成员?

最佳答案

非成员运算符是一个自由函数,与任何其他自由函数非常相似。对于 QDataStream , 关于 operator<<看起来像:

QDataStream& operator<<(QDataStream& ds, SomeType const& obj)
{
  // do stuff to write obj to the stream
  return ds;
}

在您的情况下,您可以像这样实现序列化(这只是一种方法,还有其他方法):

#include <QtCore>

class Base {
    public:
        Base() {};
        virtual ~Base() {};
    public:
        // This must be overriden by descendants to do
        // the actual serialization I/O
        virtual void serialize(QDataStream&) const = 0;
};

class Derived: public Base {
    QString member;
    public:
        Derived(QString const& str): member(str) {};
    public:
        // Do all the necessary serialization for Derived in here
        void serialize(QDataStream& ds) const {
            ds << member;
        }
};

// This is the non-member operator<< function, valid for Base
// and its derived types, that takes advantage of the virtual
// serialize function.
QDataStream& operator<<(QDataStream& ds, Base const& b)
{
    b.serialize(ds);
    return ds;
}

int main()
{
    Derived d("hello");

    QFile file("file.out");
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);

    out << d;
    return 0;
}

关于c++ - Qt 序列化,非成员 QDataStream & operator<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9453969/

相关文章:

c++ - std::setw 如何处理字符串输出?

c++ - 带轮分解的埃拉托色尼筛法

android - 在 Qt 上为 Android 设计 GUI 的技巧

qt - 带有图像的组合框

vb.net - 如何在 vb.net 中序列化和反序列化字典?

c++ - memcpy 的多线程编程

c++ - 如何分解 vector 并将其值用作函数的参数?

c++ - 在 qt 中创建 QLabels 的 QVector

c - 为什么这个 uint16_t 变量声明不起作用?

c# - 具有继承自 Dictionary<T,V> 的类的 JSON 序列化