0

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?

2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by deceptikon
0

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.

Edited by deceptikon

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.