English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C++ Operator Overloading and Overloaded Functions
Binary operators require two parameters, and here is an example of binary operators. The addition operator we usually use ( + )、subtraction operator ( - )、multiplication operator ( * ). And similarly, you can also try to overload the division operator ( / ). These all belong to binary operators. Just like the addition (+) operator.
The following example demonstrates how to overload the addition operator ( + ). Similarly, you can also try to overload the subtraction operator ( - ). And similarly, you can also try to overload the division operator ( / )
#include <iostream> using namespace std; class Box { double length; // Length double breadth; // Width double height; // 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; } // Overload + Operator used to add two Box objects 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; } }; // The main function of the program int main( ) { Box Box1; // Declare Box1Type is Box Box Box2; // Declare Box2Type is Box Box Box3; // Declare Box3Type is Box double volume = 0.0; // Store the volume in this variable // Box1 Detailed Description Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // Box2 Detailed Description Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // Box1 Volume volume = Box1.getVolume(); cout << "Box1 Volume: " << volume << endl; // Box2 Volume volume = Box2.getVolume(); cout << "Box2 Volume: " << volume << endl; // Add two objects to get Box3 Box3 = Box1 + Box2; // Box3 Volume volume = Box3.getVolume(); cout << "Box3 Volume: " << volume << endl; return 0; }
When the above code is compiled and executed, it will produce the following results:
Box1 Volume: 210 Box2 Volume: 1560 Box3 Volume: 5400