mercredi 4 mai 2022

Why overloaded operator + cannot add more than two class objects?

I have a Point class that represents a point in 2d plane. I have written a simple operator + member function . I am able to add two objects of the class Point , but not three. Why cant I add 3 objects in one line? The following code works perfectly -:

Point p(1,2) , q(3,4);
Point r = p+q;
cout<<p+q;

The following code gives an error;

Point w = p+q+r;

Error - ‘Point’ is not derived from ‘const std::reverse_iterator<_Iterator>’

Below is my implementation

class Point{

 int x;
 int y;
 static int count ; 

public:
Point() :x(0) , y(0) {count++;}
Point(int x,int y){this->x = x; this->y =y; count++;}
~Point(){    count--; }

int getx() { return x ; }
int gety() { return y ; } // can const objects call these functions.. check
void setx( int x) { this->x = x;}
void sety( int y) { this->y = y;}

friend Point operator +(Point &, Point &); 
friend std::ostream & operator << (std::ostream &,Point );
};


int Point::count = 0;

Point operator +(Point &p,Point &q) // check if const p can be passed
{
    Point sum(q.getx() + p.getx(), q.gety() + p.gety());
    return sum;
}

std::ostream & operator << (std::ostream &os,Point p)
{
    os<<"("<<p.getx()<<","<<p.gety()<<")";
    return os;

}

Aucun commentaire:

Enregistrer un commentaire