C++ - sort algorithm doesnt see my overloaded “<” operator for user-defined type.

前端 未结 2 675
情深已故
情深已故 2021-01-23 22:30

Ok so I have 1 user-defined type named fraction and it represents and ordinary fraction with a numerator and denominator. Here is the code:

class Fr         


        
2条回答
  •  伪装坚强ぢ
    2021-01-23 23:19

    Consider this code:

    Fraction a, b;
    bool res = (a < b);
    

    The second line is essentially a call to

    bool res = a.operator<(b);
    
    1. As suggested above - being const correct is going to serve you very well in a long run
    2. Define a member bool operator<(const Fraction&) const to make the sorting implementation happy or just go with the first suggestion above - be const-correct with bool operator<(const Fraction& a, const Fraction& b)

提交回复
热议问题