相关内容:
- C++ 语言支持各种关系运算符( < 、 > 、 <= 、 >= 、 == 和 !=),它们可用于比较 C++ 内置的数据类型。
- 可以重载任何一个关系运算符,重载后的关系运算符可用于比较类的对象。
代码相关内容:
- 关系运算符( < 、 > 、 <= 、 >= 、 == 和 !=);如果重载,最好是6个都重载,当然只重载1个也是可以的。
- 最好相互联系起来进行重载,让一个操作符调用另一个操作符;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using namespace std;
class Date
{
private:
int month, day, year;
public:
Date(int m=0, int d=0, int y=0):month(m),day(d),year(y)
{}
int operator==(Date& dt) const;
int operator!=(Date& dt) const;
int operator<(Date& dt) const;
int operator>(Date& dt) const;
int operator<=(Date& dt) const;
int operator>=(Date& dt) const;
};
// 重载 == 操作符;
int Date::operator==(Date& dt) const
{
return (this->month == dt.month) && (this->day == dt.day) && (this->year == dt.year);
}
// 重载 != 操作符;
int Date::operator!=(Date& dt) const
{
return !(*this == dt);
}
// 重载 < 操作符;
int Date::operator<(Date& dt) const
{
if (this->year == dt.year)
{
if (this->month == dt.month)
return this->day < dt.day;
return this->month < dt.month;
}
return this->year < dt.year;
}
int main()
{
Date d1(2, 14, 2020);
Date d2(6, 19, 2020);
Date d3(2, 14, 2020);
if (d1 < d2)
cout << "d1小于d2" << endl;
if (d1 == d3)
cout << "d1等于d3" << endl;
return 0;
}代码执行结果: