0

大家好,我有一个继承自 QObject 的 foo 类,我想使用 QSettings 进行序列化。foo.h 中的代码

namespace GUI
{
class Foo : public QObject
{
Q_OBJECT
Q_PROPERTY(QString mem1 READ mem1 WRITE setMem1 NOTIFY mem1Changed)
Q_PROPERTY(QString mem2 READ mem2 WRITE setMem2 NOTIFY mem2Changed)
Q_PROPERTY(int mem3 READ mem3 WRITE setMem3 NOTIFY mem3Changed)
public:
explicit Foo(QObject *parent = 0);
virtual ~Foo();
....
friend QDataStream& operator>>(QDataStream& in, Foo* v);
friend QDataStream& operator<<(QDataStream& out, const Foo* v);
private:

QString mem1;
QString mem2;
int mem3;

};
}
Q_DECLARE_METATYPE(GUI::Foo*)

Foo.cpp 中的代码

 QDataStream& operator<<(QDataStream& out, const Foo* v) {
 out << v->mem1 << v->mem2<< v->mem3;
 return out;
 }

 QDataStream& operator>>(QDataStream& in, Foo& v) {
 in >>v->mem1;
 in >>v->mem2;
 in >>v->mem3
 return in;
 }

main.cpp 中的代码

qRegisterMetaTypeStreamOperators<GUI::Foo*>("GUI::Foo*");
GUI::Foo c1 ;
QSettings saver;
saver.setValue("test1",QVariant::fromValue(&c1));
QSettings loader;
QVariant value = loader.value("test1");
GUI::Foo* t = value.value<GUI::Foo*>();

现在编译正常但是当我调试它时,我得到异常触发的读取访问冲突

 QDataStream& operator>>(QDataStream& in, Foo& v) {
 in >>v->mem1; <- here i am getting read access violation and v is showing to be null
 in >>v->mem2;
 in >>v->mem3
 return in;
 }

需要注意的重要一件事是,如果我将朋友功能更改为

QDataStream& operator>>(QDataStream& in, Foo* v) {
QString var1;
QString var2;
int var3;
in >> var1;
in >> var2;
in >> var3;
return in;
} 

我确实在 var1、var2 和 var3 中得到了正确的值。

有人可以告诉我我做错了什么,我该如何纠正它提前谢谢

4

0 回答 0