我使用读/写 QObjects 是真的吗?我用它序列化一个类,但是反序列化它不是原始类!
我能做些什么?
这是我的基类标题:
class Base : public QObject
{
Q_OBJECT
public:
explicit Base(QObject *parent = 0);
};
QDataStream &operator<<(QDataStream &ds, const Base &obj);
QDataStream &operator>>(QDataStream &ds, Base &obj) ;
.cpp 是:
Base::Base(QObject *parent) :
QObject(parent)
{
}
QDataStream &operator<<(QDataStream &ds, const Base &obj) {
for(int i=0; i<obj.metaObject()->propertyCount(); ++i) {
if(obj.metaObject()->property(i).isStored(&obj)) {
ds << obj.metaObject()->property(i).read(&obj);
}
}
return ds;
}
QDataStream &operator>>(QDataStream &ds, Base &obj) {
QVariant var;
for(int i=0; i<obj.metaObject()->propertyCount(); ++i) {
if(obj.metaObject()->property(i).isStored(&obj)) {
ds >> var;
obj.metaObject()->property(i).write(&obj, var);
}
}
return ds;
}
我有一个从 base 继承的学生类:
class student : public Base
{
public:
student();
int id;
QString Name;
};
这是我的主要内容:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
student G;
student G2;
G.id=30;
G.Name="erfan";
qDebug()<<G.id<<G.Name;
QFile file("file.dat");
file.open(QIODevice::WriteOnly);
QDataStream out(&file); // we will serialize the data into the file
out <<G;
qDebug()<<G2.id<<G2.Name;
file.close();
file.open(QIODevice::ReadOnly);
out>>G2;
qDebug()<<G2.id<<G2.Name;
return a.exec();
}
这是我的输出:
30 "erfan"
1498018562 ""
1498018562 ""