其他重載運算符實例 參考鏈接:https://www.runoob.com/cplusplus/cpp-overloading.html
您可以重定義或重載大部分 C++ 內置的運算符。這樣,您就能使用自定義類型的運算符。
重載的運算符是帶有特殊名稱的函數,函數名是由關鍵字 operator 和其后要重載的運算符符號構成的。與其他函數一樣,重載運算符有一個返回類型和一個參數列表。
Box operator+(const Box&);
聲明加法運算符用於把兩個 Box 對象相加,返回最終的 Box 對象。大多數的重載運算符可被定義為普通的非成員函數或者被定義為類成員函數。如果我們定義上面的函數為類的非成員函數,那么我們需要為每次操作傳遞兩個參數,如下所示:
Box operator+(const Box&, const Box&);
下面的實例使用成員函數演示了運算符重載的概念。在這里,對象作為參數進行傳遞,對象的屬性使用 this 運算符進行訪問,如下所示:
實例
#include <iostream> using namespace std; class Box { 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; } private: double length; // 長度 double breadth; // 寬度 double height; // 高度 }; // 程序的主函數 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; }