Less operator cannot be overloaded as a member function

I want to use classas keyin map, so I overload operator+. It works well if I overload it as a friend function. When I overload it as a member function inside a class, it causes a compilation error.

error C2678: binary '<': an operator was not found that accepts a left operand of type 'const Syl' (or there is no acceptable conversion) '.

In detail, this does not compile and does not generate a compilation error:

Syl.h

bool operator< (const Syl& rhs);

Syl.cpp

bool Syl::operator< (const Syl& rhs) {  return false; }

While this is compiling.

Syl.h

friend bool operator< (const Syl& lhs, const Syl& rhs);

Syl.cpp

bool operator< (const Syl& lhs, const Syl& rhs) {   return false; }

I do not know why. I know that the <operator is binary, but anyway, to overload it as a member of a function?

+4
2

, -, operator<, , . , , , const , ..

class Syl {
  ...
  public:
  bool operator<(const Syl& rhs) const;  
}

STL, std::map.


- :

friend bool operator<(Syl& lhs, const Syl& rhs);

const lhs. - , . l- lhs. - , `` no operator found... ''. STL std::map , , , , - .

+3

, a b Syl, ( ) a < b, a is const ,

, operator<()

bool operator< (const Syl& rhs) const;    // note the trailing const

trailing const, a < b, a const (.. operator<() ).

, , const .

, <, EITHER . const .

, , . - ( , a < b).

+2

Source: https://habr.com/ru/post/1670814/


All Articles