C++ 二元運算符重載
二元運算符需要兩個參數,下麵是二元運算符的實例。我們平常使用的加運算符( + )、減運算符( - )、乘運算符( * )和除運算符( / )都屬於二元運算符。就像加(+)運算符。
下麵的實例演示了如何重載加運算符( + )。類似地,您也可以嘗試重載減運算符( - )和除運算符( / )。
實例
#include <iostream>
using namespace std;
class Box
{
   double length;      // 長度
   double breadth;     // 寬度
   double height;      // 高度
public:
   double getVolume(void)
   {
      return length * breadth * height;
   }
   void setLength( double len )
   {
       length = len;
   }
   void setBreadth( double bre )
   {
       breadth = bre;
   }
   void setHeight( double hei )
   {
       height = hei;
   }
   // 重載 + 運算符,用於把兩個 Box 對象相加
   Box operator+(const Box& b)
   {
      Box box;
      box.length = this->length + b.length;
      box.breadth = this->breadth + b.breadth;
      box.height = this->height + b.height;
      return box;
   }
};
// 程式的主函數
int main( )
{
   Box Box1;                // 聲明 Box1,類型為 Box
   Box Box2;                // 聲明 Box2,類型為 Box
   Box Box3;                // 聲明 Box3,類型為 Box
   double volume = 0.0;     // 把體積存儲在該變數中
   // Box1 詳述
   Box1.setLength(6.0);
   Box1.setBreadth(7.0);
   Box1.setHeight(5.0);
   // Box2 詳述
   Box2.setLength(12.0);
   Box2.setBreadth(13.0);
   Box2.setHeight(10.0);
   // Box1 的體積
   volume = Box1.getVolume();
   cout << "Volume of Box1 : " << volume <<endl;
   // Box2 的體積
   volume = Box2.getVolume();
   cout << "Volume of Box2 : " << volume <<endl;
   // 把兩個對象相加,得到 Box3
   Box3 = Box1 + Box2;
   // Box3 的體積
   volume = Box3.getVolume();
   cout << "Volume of Box3 : " << volume <<endl;
   return 0;
}
當上面的代碼被編譯和執行時,它會產生下列結果:
Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400

 C++ 重載運算符和重載函數