C++ 二元运算符重载


二元运算符需要两个参数,下面是二元运算符的实例。我们平常使用的加运算符( + )、减运算符( - )、乘运算符( * )和除运算符( / )都属于二元运算符。就像加(+)运算符。

下面的实例演示了如何重载加运算符( + )。类似地,您也可以尝试重载减运算符( - )和除运算符( / )。

  1. #include <iostream>
  2. using namespace std;
  3. class Box
  4. {
  5. double length; // 长度
  6. double breadth; // 宽度
  7. double height; // 高度
  8. public:
  9. double getVolume(void)
  10. {
  11. return length * breadth * height;
  12. }
  13. void setLength( double len )
  14. {
  15. length = len;
  16. }
  17. void setBreadth( double bre )
  18. {
  19. breadth = bre;
  20. }
  21. void setHeight( double hei )
  22. {
  23. height = hei;
  24. }
  25. // 重载 + 运算符,用于把两个 Box 对象相加
  26. Box operator+(const Box& b)
  27. {
  28. Box box;
  29. box.length = this->length + b.length;
  30. box.breadth = this->breadth + b.breadth;
  31. box.height = this->height + b.height;
  32. return box;
  33. }
  34. };
  35. // 程序的主函数
  36. int main( )
  37. {
  38. Box Box1; // 声明 Box1,类型为 Box
  39. Box Box2; // 声明 Box2,类型为 Box
  40. Box Box3; // 声明 Box3,类型为 Box
  41. double volume = 0.0; // 把体积存储在该变量中
  42. // Box1 详述
  43. Box1.setLength(6.0);
  44. Box1.setBreadth(7.0);
  45. Box1.setHeight(5.0);
  46. // Box2 详述
  47. Box2.setLength(12.0);
  48. Box2.setBreadth(13.0);
  49. Box2.setHeight(10.0);
  50. // Box1 的体积
  51. volume = Box1.getVolume();
  52. cout << "Volume of Box1 : " << volume <<endl;
  53. // Box2 的体积
  54. volume = Box2.getVolume();
  55. cout << "Volume of Box2 : " << volume <<endl;
  56. // 把两个对象相加,得到 Box3
  57. Box3 = Box1 + Box2;
  58. // Box3 的体积
  59. volume = Box3.getVolume();
  60. cout << "Volume of Box3 : " << volume <<endl;
  61. return 0;
  62. }

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

  1. Volume of Box1 : 210
  2. Volume of Box2 : 1560
  3. Volume of Box3 : 5400