Hello. This is my first problem post on Daniweb so feel free to overload me with info even outside the scope of this overloading problem.
I have a class Point where I have overloaded the + operator and I'm trying to overload "operator=" so that I can right something like:
Point newPos = myPos + yourPos.
g++ gives me this error (Lines 40 and 21):
In function `int main()':|
|40|error: no match for 'operator=' in 'newPos = (&myPos)->Point::operator+(((Point&)(&yourPos)))'|
|21|note: candidates are: Point Point::operator=(Point&)|
||=== Build finished: 1 errors, 0 warnings ===|
Here's my code:
#include <iostream>
using namespace std;
class Point
{
private:
float itsX, itsY, itsZ;
public:
Point(float x = 0.0, float y = 0.0, float z = 0.0): itsX(x), itsY(y), itsZ(z)
{}
float getX() const { return itsX; }
float getY() const { return itsY; }
float getZ() const { return itsZ; }
Point operator +(Point &p) const
{
return Point(itsX + p.getX(), itsY + p.getY(), itsZ + p.getZ());
}
Point operator =(Point &p)
{
itsX = p.getX();
itsY = p.getX(); //yes, getX uses purposely throughout for testing
itsZ = p.getX();
return *this;
}
};
ostream& operator <<(ostream &stream, Point &p)
{
stream << p.getX() << " " << p.getY() << " " << p.getZ();
return stream;
}
int main()
{
Point myPos(1, 2, 3), yourPos(.1, .2, .3);
Point newPos;
newPos = myPos + yourPos;
cout << "myPos location:\n" << myPos << endl;
cout << "yourPos location:\n" << yourPos << endl;
cout << "newPos location:\n" << newPos << endl;
return 0;
}
Strangely if i combine lines 39 - 40 as:
Point newPos = myPos + yourPos;
the default equal seems to be used and not the overloaded one and the program compiles.
And also if i change the declaration of the overload to:
Point operator =(Point p) // no longer passing a reference
the program works as i want. Although here again if i used:
Point newPos = myPos + yourPos;
A shallow copy seems to still be performed, ignoring the redefined equal.