PDA

View Full Version : Operator overloading << error: must take exactly one argument



nomiz
11th March 2012, 12:48
Hi all!

I can't get my head around the compile error I get when overloading the << operator:
error: ‘QDataStream& Coordinate::operator<<(QDataStream&, const Coordinate&)’ must take exactly one argument

Here is the code:

coordinate.h:


class Coordinate
{
public:
Coordinate();

double x, y, z;

// output
QDataStream &operator <<(QDataStream& out, const Coordinate& c);
};

coordinate.cpp:


#include "coordinate.h"

Coordinate::Coordinate()
{
x = y = z = 0.;
}

QDataStream& operator <<(QDataStream& out, const Coordinate& c)
{
out << "(" << c.x << ", " << c.y << ", " << c.z << ")";
return out;
}


What is wrong / am I not getting?

Thanks!

wysota
11th March 2012, 14:16
The operator should be a standalone function and not a method of your class.

Zlatomir
11th March 2012, 14:19
If you want to make the data members private you can add friend operator inside your class:


class Coordinate
{
public:
Coordinate();
// output
friend QDataStream &operator <<(QDataStream& out, const Coordinate& c);
private:
double x, y, z;
};

nomiz
11th March 2012, 15:43
The operator should be a standalone function and not a method of your class.

Worked! Thank you!

Why does operator== not give any troubles?


If you want to make the data members private you can add friend operator inside your class:

Ok, thanks for your info!

wysota
11th March 2012, 16:15
Worked! Thank you!

Why does operator== not give any troubles?

If you put the operator inside the class definition, then the operator takes the current object ("this") implicitly as its first parameter.

So operator== comparing A against B can be placed in class A but not in B (or it can be a standalone function taking two parameters -- A and B). If you have a standalone operator << that takes QDataStream and MyStruct as its parameters, you could put it in QDataStream class but not in MyStruct class. Since in C++ you can't modify a class that has already been defined, you can't put it in QDataStream class and you're left with the standalone option.

nomiz
11th March 2012, 16:29
Aha! Thanks alot. I'll buy and read a proper C++ book ;)

wysota
11th March 2012, 16:37
That's usually a good idea :)