C++ 关系运算符重载


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

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

下面的实例演示了如何重载 < 运算符,类似地,您也可以尝试重载其他的关系运算符。

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

当上面的代码被编译和执行时,它会产生下列结果:

  1. D2 is less than D1