二元運算符需要兩個參數(shù),下面是二元運算符的示例。我們平常使用的加運算符( + )、減運算符( - )、乘運算符( * )和除運算符( / )都屬于二元運算符。就像加(+)運算符。
下面的示例演示了如何重載加運算符( + )。類似地,您也可以嘗試重載減運算符( - )和除運算符( / )。
#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; } }; // 程序的主函數(shù) 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 << "Box1 的體積 : " << volume <<endl; // Box2 的體積 volume = Box2.getVolume(); cout << "Box2 的體積 : " << volume <<endl; // 把兩個對象相加,得到 Box3 Box3 = Box1 + Box2; // Box3 的體積 volume = Box3.getVolume(); cout << "Box3 的體積 : " << volume <<endl; return 0; }
當上面的代碼被編譯和執(zhí)行時,它會產生下列結果:
Box1 的體積 : 210 Box2 的體積 : 1560 Box3 的體積 : 5400