PDA

View Full Version : QDataSteam.



wookoon
13th September 2010, 04:53
I want write a class which is inherit from QObject to the file with QDataStream, so I overload operator << and operator >>.


Class C : public QObject
{
Q_OBJECT
......
friend QDataStream & operator << (QDataStream &dataStream, C &c);
friend QDataStream & operator >> (QDataStream &dataStream, C &C);
.......
}

.................
QDataStream & operator << (QDataStream &dataStream, C &c)
{

}

QDataStream & operator >> (QDataStream &dataStream, C &c)
{

}


but it can't compile success.The error is:multiple definition of "operator" <<(QDataStream&,C&)
multiple definition of "operator" >>(QDataStream&,C&)

if this class is not inherit from the QObject and delete macro Q_OBJECT, then it will compile success. So What's the problem....?

tbscope
13th September 2010, 06:34
Obviously you can not have the same function or operator twice.
Your code shows that you implemented the >> operator twice (the same).

wysota
13th September 2010, 16:27
Bodies of the operators should be moved to a .cpp file. If you place them in a header file, they will be defined each time the file is included somewhere and you'll be getting multiple definitions. An alternative is to declare those functions as inline.

By the way, the << operator should be getting a const object. Otherwise you won't be able to use the operator in some contexts (i.e. some const methods).