比较运算符: 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==
.
别看: 但等价性和相等性是有区别的
以 int i
和 int j
为例:
!(i < j) && !(j < i)
为等价性, 则i
既不小于、也不大于j
.i == j
为相等性, 则对于函数f(int value)
,f(i)
与f(j)
相同.
1bool is_square_less(int i, int j) {
2 return i * i < j * j;
3}
4
5void print(int value) {
6 std::cout << value << '\n';
7}
8
9int main() {
10 int i = -1;
11 int j = 1;
12
13 !is_square_less(i, j); // 在平方小于偏序关系下, i 和 j 等价
14 !is_square_less(j, i);
15
16 print(i); // 但 i 和 j 并不相等
17 print(j);
18}