PDA

View Full Version : QDataStream class/struct & stream operators



darksaga
1st August 2008, 18:58
Hi everybody,

following problem:

I'm using a struct comparable to this one in my code:


#ifndef STRUCT_MYPOINT
#define STRUCT_MYPOINT
#include <QDataStream>

typedef struct MyPoint {
int x;
int y;
}MyPoint;

QDataStream &operator<<(QDataStream &out, const MyPoint &p)
{
out << (qint32)p.x;
out << (qint32)p.y;
return out;
}

QDataStream &operator>>(QDataStream &in, MyPoint &p)
{
in >> (qint32)p.x;
in >> (qint32)p.y;
return in;
}
#endif


this struct is defined in a seperate *.h file, lets say "mypoint.h"

my code works fine if I compile it with Visual Studio .Net & Qt 4.4.0

now I also try to compile my code under a linux environment using qt 4.4.0 and gcc 4.2.0

now the same code won't compile anymore.
I get a long list of errors messages, with the important ones saying

no match for 'operator>>'
no match for 'operator<<'

searched the net for some kind of solution, but haven't found one.
only thing I learned is that I must add, at least, the following lines to my code:


friend Q_CORE_EXPORT QDataStream &operator<<(QDataStream &, const MyPoint &);
friend Q_CORE_EXPORT QDataStream &operator>>(QDataStream &, MyPoint &);


added these lines to my struct:



#ifndef STRUCT_MYPOINT
#define STRUCT_MYPOINT
#include <QDataStream>

typedef struct MyPoint {
int x;
int y;
}MyPoint;

QDataStream &operator<<(QDataStream &out, const MyPoint &p)
{
out << (qint32)p.x;
out << (qint32)p.y;
return out;
}

QDataStream &operator>>(QDataStream &in, MyPoint &p)
{
in >> (qint32)p.x;
in >> (qint32)p.y;
return in;
}
friend Q_CORE_EXPORT QDataStream &operator<<(QDataStream &, const MyPoint &);
friend Q_CORE_EXPORT QDataStream &operator>>(QDataStream &, MyPoint &);
#endif



but the problem remains.

So what am I missing/doing wrong???

greetz
darksaga

caduel
1st August 2008, 20:40
side note: the typedef around the struct is not necessary in C++.


QDataStream &operator>>(QDataStream &in, MyPoint &p)
{
in >> (qint32)p.x;
in >> (qint32)p.y;
return in;
}

I would assume that you can't cast p.x to a value and stream into this value.
Probably something like

qint32 tmp;
in >> tmp;
p.x = tmp;
would be more appropriate.

Apart from that:
Please show us the code that produces the error messages and the complete error message, too.


And finally,
I suggest to just declare the output function in the header (and implement them in some .cpp file). Otherwise you will end up with multiple definitions of those functions and get linker errors.

HTH