uacs2024

导航

C++ 关系运算符重载

C++ 语言支持各种关系运算符( < 、 > 、 <= 、 >= 、 == 等等),它们可用于比较 C++ 内置的数据类型。

您可以重载任何一个关系运算符,重载后的关系运算符可用于比较类的对象。

 1 #include <iostream>
 2 using namespace std;
 3  
 4 class Distance
 5 {
 6    private:
 7       int feet;             // 0 到无穷
 8       int inches;           // 0 到 12
 9    public:
10       // 所需的构造函数
11       Distance(){
12          feet = 0;
13          inches = 0;
14       }
15       Distance(int f, int i){
16          feet = f;
17          inches = i;
18       }
19       // 显示距离的方法
20       void displayDistance()
21       {
22          cout << "F: " << feet << " I:" << inches <<endl;
23       }
24       // 重载负运算符( - )
25       Distance operator- ()  
26       {
27          feet = -feet;
28          inches = -inches;
29          return Distance(feet, inches);
30       }
31       // 重载小于运算符( < )
32       bool operator <(const Distance& d)
33       {
34          if(feet < d.feet)
35          {
36             return true;
37          }
38          if(feet == d.feet && inches < d.inches)
39          {
40             return true;
41          }
42          return false;
43       }
44 };
45 int main()
46 {
47    Distance D1(11, 10), D2(5, 11);
48  
49    if( D1 < D2 )
50    {
51       cout << "D1 is less than D2 " << endl;
52    }
53    else
54    {
55       cout << "D2 is less than D1 " << endl;
56    }
57    return 0;
58 }

结果

D2 is less than D1

 

posted on 2024-03-02 21:00  ᶜʸᵃⁿ  阅读(5)  评论(0编辑  收藏  举报