首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Qt序列化、非成员QDataStream和operator<<

问Qt序列化、非成员QDataStream和operator<<
EN

Stack Overflow用户
提问于 2012-02-26 14:39:21
回答 1查看 1.6K关注 0票数 1

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

我希望这样做--所有子类还必须实现一个操作符来进行序列化:

除了这里记录的重载流运算符之外,您可能希望序列化到QDataStream的任何Qt类都会将适当的流运算符声明为该类的非成员:

我甚至不确定如何做一个抽象运算符,但是如何定义它的非成员呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-26 14:54:08

非成员运算符是一个自由函数,就像任何其他自由函数一样。对于QDataStream,在operator<<上应该如下所示:

代码语言:javascript
复制
QDataStream& operator<<(QDataStream& ds, SomeType const& obj)
{
  // do stuff to write obj to the stream
  return ds;
}

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

代码语言:javascript
复制
#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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9453969

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档