Click the original link to open the link.
What is Operator overload?
Operator overloading can be divided into two parts: "operator" and "overload ". When it comes to overloading, it should be no stranger. This is a kind of polymorphism during compilation. In fact, overloading can be divided into function overloading and operator overloading. The difference between operator overloading and function Overloading is that operator overloading must be an operator. Let's take a look at the so-called Operator Overloading:
#include <iostream> using namespace std; int main() { int a = 2 , b = 3; float c = 2.1f , d = 1.2f; cout<<"a + b = "<<a+b<<endl; cout<<"c + d = "<<c+d<<endl; return 0; }
We can see that the operator "+" is complete.FloatAndIntTwo types of addition calculation, which is the heavy load of operators. These built-in types of Operator Overloading have been implemented, but what if we want to implement a similar addition operation for the classes we have already written ?? For example, now there is such a point class. To add two vertices, the result is that the horizontal and vertical coordinates must be added. At this time, we need to write an operator to reload the function.
View code # include <iostream> using namespace STD; Class Point {Double X; Double Y; public: Double get_x () {return X;} double get_y () {return y ;} point (Double X = 0.0, Double Y = 0.0): x (x), y (y) {}; point operator + (point P );}; // overload operator "+" point: Operator + (point P) {Double X = This-> X + P. x; Double Y = This-> Y + P. y; point tmp_p (x, y); Return tmp_p;} int main () {Point P1 (1.2, 3.1); point P2 (1.1, 3.2 ); point P3 = p1 + P2; cout <p3.get _ x () <"" <p3.get _ y () <Endl; return 0 ;}