gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:29:19 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com