我有一个类IDocument,它用作一些类的接口。它有一些抽象方法(virtual ... = 0)。
我希望这样做--所有子类还必须实现一个操作符来进行序列化:
除了这里记录的重载流运算符之外,您可能希望序列化到QDataStream的任何Qt类都会将适当的流运算符声明为该类的非成员:
我甚至不确定如何做一个抽象运算符,但是如何定义它的非成员呢?
发布于 2012-02-26 14:54:08
非成员运算符是一个自由函数,就像任何其他自由函数一样。对于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;
}https://stackoverflow.com/questions/9453969
复制相似问题