New Pea
New Pea

Reputation: 141

Overloading operator< containing class object

Having trouble with overloading operator<. I am trying to overload the operator< so that I can sort my Line2D object based on pt1's x. But I am having trouble figuring out how to declare the function.

I am getting the error:

object has type qualifiers that are not compatible with the member function "Point2D::getX".

What I have tried: removing const, putting Point2D &l2dobj instead.

class Line2D
{
private:
   Point2D pt1;
   Point2D pt2;

public:
   bool operator<( const Line2D &l2dobj)
   {
       return (pt1.getX() < l2dobj.pt1.getX());
   }
}


class Point2D
{
protected:
   int x;
   int y;
public:
   int getX();
   int getY();
}

Upvotes: 1

Views: 67

Answers (1)

bruno
bruno

Reputation: 32596

Point2D::getX doesn't accept const instance, you cannot apply it on l2dobj while it is a const reference, change getX (and a priori getY) to :

class Point2D
{
protected:
   int x;
   int y;
public:
   int getX() const;
   int getY() const;
};

As a general way declare the methods const the more you can, and same for their parameters

Upvotes: 3

Related Questions