Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt serialization boolean with QDataStream

I'm having an error while trying to serialize my custom class. I am using the QDataStream operator << and >> in order 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;
}
like image 410
Skwateur Avatar asked Jan 13 '23 10:01

Skwateur


1 Answers

You're most likely not including the relevant headers. I can reproduce your issue when QDataStream is not included.

Since your members are, according to your comment, private, your class must also befriend the stream operator.

The following compiles 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; }; is equivalent to class Foo { public: int a; int b; };. A C++ struct is simply a class with the default access specifier set to public. A class has the default access specifier set to private. Otherwise, there's no difference.

like image 179
Kuba hasn't forgotten Monica Avatar answered Jan 22 '23 13:01

Kuba hasn't forgotten Monica