It is impossible to overload the comparison operator "<". I use Qt.
point.h

class Point { private: double x; double y; double z; ... public: double getX(); double getY(); double getZ(); ... friend bool operator<(Point &first, Point &sec); } 

point.cpp

 ... bool Point::operator<(Point &first, Point &sec) { return sqrt(first.getX()*first.getX() + first.getY()*first.getY() + first.getZ()*first.getZ()) < sqrt(sec.getX()*sec.getX() + sec.getY()*sec.getY() + sec.getZ()*sec.getZ()); } 

main.cpp

 ... QList<Point> list; ... qSort(list.begin(), list.end()); ... 

With this implementation, it gives an error:

 ...\point.cpp:23: ошибка: 'bool Point::operator<(Point&, Point&)' must take exactly one argument bool Point::operator<(Point &first, Point &sec) ^ 

If I remove the second argument: point.h

 ... friend bool operator<(Point &first); ... 

point.cpp

 ... bool Point::operator<(Point &first) { return sqrt(first.getX()*first.getX() + first.getY()*first.getY() + first.getZ()*first.getZ()) < sqrt(x*x+y*y+z*z); } ... 

That gives out:

 ...\point.h:46: ошибка: 'bool operator<(Point&)' must take exactly two arguments friend bool operator<(Point &first); ^ 

Tell me what the problem is and how to make it work.


Writing to .h inside the class

 friend bool operator<(const Point &first, const Point &sec); 

in .cpp

 bool operator<(Point const &first, Point const &sec){ return sqrt(first.getX()*first.getX() + first.getY()*first.getY() + first.getZ()*first.getZ()) < sqrt(sec.getX()*sec.getX() + sec.getY()*sec.getY() + sec.getZ()*sec.getZ()); } 

It gives a number of similar errors (for each get)

 ...\point.cpp:24: ошибка: passing 'const Point' as 'this' argument of 'double Point::getX()' discards qualifiers [-fpermissive] return sqrt(first.getX()*first.getX() + first.getY()*first.getY() + first.getZ()*first.getZ()) < ^ 
  • irrelevant, but operator< for points does not look very natural, because the set of points does not form an order. - Fat-Zer

1 answer 1

The declared operator does not match the implemented one.

 friend bool operator<(Point &first, Point &sec); // объявляет его как свободную функци. 

accordingly, the implementation must be without a class prefix:

 bool operator<(Point &first, Point &sec) 

And const not enough in the signature:

 (Point const & first, Point const & sec) 

and you can do without a friend and declare it outside the class as the operator seems to call only public methods, without requiring access to protected and private .

  • Corrected, but now gives other errors. - Vasily
  • @ Vasily This is because there are not enough const qualifiers for the getters. double getX() const; - VTT
  • Yes indeed. Now everything works. Thank. - Vasily