Hi,
I am new on this site, i have some issues about OOP in C++ operator overloading.
I try to do add a two numbers using overloading operator "+" in more ways :
1). First way is : const Point operator+(const Point& point) const.
So i add two numbers in this way using an reference to Point class like parameter :
const Point Point::operator+(const Point& point) const
{
return Point(this->x + point.x, this->y + point.y);
}
This variant works.
2). Second way is : const Point operator+(const int Value) const.
I add two numbers with a constant integer value like parameter :
const Point Point::operator+(const int Value) const
{
return Point(this->x + Value, this->y + Value);
}
This variant works, also.
3). The third way : const Point::operator+(const Point& point1, const Point& point2).
but
this code is not ok. I receive an error :
error: 'const Point Point::operator+(const Point&, const Point&)' must take either zero or one argument.
#include <iostream>
using namespace std;
class Point
{
private:
int x;
int y;
public:
Point(int x = 0, int y = 0);
int getX() const;
int getY() const;
void setX(int X);
void setY(int y);
void print() const;
const Point operator+(const Point& point1, const Point& point2);
};
Point::Point(int a, int b)
{
x = a;
y = b;
}
int Point::getX() const
{
return x;
}
int Point::getY() const
{
return y;
}
void Point::setX(int X)
{
this->x = X;
}
void Point::setY(int Y)
{
this->y = Y;
}
void Point::print() const
{
cout << "\n x = " << x << "\n\n y = " << y <<endl<<endl;
}
const Point::operator+(const Point& point1, const Point& point2)
{
return Point(point1.x + point2.x, point2.y + point2.y);
}
int main()
{
Point p1(2, 8), p2(4, 5);
Point p3 = p1 + p2;
p1.print();
p2.print();
p3.print();
Point p5 = p1 + p2 + p3;
p5.print();
return 0;
}