比较运算符: operator<、operator==

比较运算符: operator<operator==#

等价性 (偏序关系)#

定义 operator<, 然后用它定义其他.

 1class Widget {
 2 public:
 3  // 定义 operator< 以获得严格弱序
 4  friend bool operator<(Widget const& lhs, Widget const& rhs) {
 5    return lhs.value_ < rhs.value_;
 6  }
 7
 8  // 通过 operator< 定义其他关系运算符
 9  friend bool operator>(Widget const& lhs, Widget const& rhs) {
10    return rhs < lhs;
11  }
12  friend bool operator<=(Widget const& lhs, Widget const& rhs) {
13    return !(lhs > rhs);
14  }
15  friend bool operator>=(Widget const& lhs, Widget const& rhs) {
16    return !(lhs < rhs);
17  }
18
19 private:
20  int value_;
21};

相等性#

定义 operator==, 然后用它定义 operator!=.

 1class Widget {
 2 public:
 3  // 定义 operator==
 4  friend bool operator==(Widget const& lhs, Widget const& rhs) {
 5    return lhs.value_ == rhs.value_;
 6  }
 7
 8  // 通过 operator== 定义 operator!=
 9  friend bool operator!=(Widget const& lhs, Widget const& rhs) {
10    return !(lhs == rhs);
11  }
12
13 private:
14  int value_;
15};

注意传参应该传 Widget const& widget 而非 Widget widget. 为什么呢? 所谓拷贝, 是得到与原对象相等的对象, 而我们此处正是在定义什么是相等.

提示

如果定义了 operator<,你也可以基于它定义 operator==.