Qt serialization logical with QDataStream

I got an error while trying to serialize my custom class. I use the QDataStream <and → operator to write and read my object.

The error occurs when I try to write or read a boolean:

error: ambiguous overload for 'operator<<' (operand types are 'QDataStream' and 'const bool') 
 QDataStream & operator << (QDataStream & out, const sys_settings & Value) { out << Value.myBool << Value.someString; return out; } 
 QDataStream & operator >> (QDataStream & in, sys_settings & Value) { in >> Value.myBool; in >> Value.someString return in; } 
+4
source share
1 answer

Most likely, you will not include the corresponding headings. I can reproduce your problem if QDataStream not enabled.

Since your members are private according to your comment, your class also needs to make friends with the stream operator.

The following compilation is OK:

 #include <QString> #include <QDataStream> class C { // Everything here is private, the stream operator must be friends! bool b; QString s; C() : b(false) {} friend QDataStream & operator << (QDataStream & out, const C & val); }; QDataStream & operator << (QDataStream & out, const C & val) { out << val.b << val.s; return out; } 

Note that struct Foo { int a; int b; }; struct Foo { int a; int b; }; equivalent to class Foo { public: int a; int b; }; class Foo { public: int a; int b; }; . C ++ struct is just a class with a default access specifier set to the public. A class has a default access specifier set to private. Otherwise there is no difference.

+7
source

Source: https://habr.com/ru/post/1500917/


All Articles