Operator overloading << error: must take exactly one argument
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:
Code:
class Coordinate
{
public:
Coordinate();
double x, y, z;
// output
QDataStream &operator <<
(QDataStream
& out,
const Coordinate
& c
);
};
coordinate.cpp:
Code:
#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!
Re: Operator overloading << error: must take exactly one argument
The operator should be a standalone function and not a method of your class.
Re: Operator overloading << error: must take exactly one argument
If you want to make the data members private you can add friend operator inside your class:
Code:
class Coordinate
{
public:
Coordinate();
// output
friend QDataStream &operator <<
(QDataStream
& out,
const Coordinate
& c
);
private:
double x, y, z;
};
Re: Operator overloading << error: must take exactly one argument
Quote:
Originally Posted by
wysota
The operator should be a standalone function and not a method of your class.
Worked! Thank you!
Why does operator== not give any troubles?
Quote:
Originally Posted by
Zlatomir
If you want to make the data members private you can add friend operator inside your class:
Ok, thanks for your info!
Re: Operator overloading << error: must take exactly one argument
Quote:
Originally Posted by
nomiz
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.
Re: Operator overloading << error: must take exactly one argument
Aha! Thanks alot. I'll buy and read a proper C++ book ;)
Re: Operator overloading << error: must take exactly one argument
That's usually a good idea :)