c++ less operator overload, which way to use?

后端 未结 3 1315
时光取名叫无心
时光取名叫无心 2021-02-12 13:25

For example: in a C++ header file, if I defined a struct Record and I would like to use it for possible sorting so that I want to overload the less operator

相关标签:
3条回答
  • 2021-02-12 13:41

    Favor in-class unless it cannot be in-class because first argument is the wrong type.

    0 讨论(0)
  • 2021-02-12 13:49

    The best way to define the less operator is:

    struct Record{
        (...)
        const bool operator < ( const Record &r ) const{
            return ( num < r.num );
        }
    };
    
    0 讨论(0)
  • 2021-02-12 14:01

    They are essentially the same, other than the first being non-const and allowing you to modify itself.

    I prefer the second for 2 reasons:

    1. It doesn't have to be a friend.
    2. lhs does not have to be a Record
    0 讨论(0)
提交回复
热议问题