Start New Discussion within our Software Development Community

ASsuming in class , i have:

class math
{
    private:
        int x,y;
    public:  

      bool operator>(const math& );
      bool operator<(const math& );
}
 bool Point2D::operator>(const math &p)
 {
        return (this->x > p.x);
 }
 bool Point2D::operator<(const math &p )
 {
        return (this->x < p.x);
 }
  bool Point2D::operator>(const math &p)
 {
        return (this->y > p.y);
 }
 bool Point2D::operator<(const math &p )
 {
        return (this->y < p.y);
 }

I want to compare each x value whether it larger or smaller(only compare X value) , the same thing go to Y value.

How do i implement this by using overload operator?

You can't overload the same operator with the same signature more than once because then the two overloads would be ambiguous. Your best option here is to discard operator overloading and use regular member functions, with the simplest solution being one per task:

bool Point2D::lessX(const math& p) { return x < p.x; }
bool Point2D::lessY(const math& p) { return y < p.y; }
bool Point2D::greaterX(const math& p) { return x > p.x; }
bool Point2D::greaterY(const math& p) { return y > p.y; }

But I'm curious why the comparison won't work as checking x first, then y if the x's are equal:

bool Point2D::operator<(const math& p) { return x != p.x ? x < p.x : y < p.y; }
bool Point2D::operator>(const math& p) { return x != p.x ? x > p.x : y > p.y; }

That's the usual method of doing a comparison with multiple terms.

This article has been dead for over six months. Start a new discussion instead.