What is Operator overload? Overload is an overload concept in object-oriented systems. It is an incomplete embodiment of object polymorphism. The so-called Operator Overloading means to redefine existing operators and assign them another function to adapt to different data types. Why is Operator overloading required? For example: 1 + 1 = 2 This is the first cup of water that the system can recognize and calculate + 1 cup of water = 2 cups of water by default. Then the system cannot determine what you want to do. In this case, you need to redefine the "+" operator to realize the "and" operation between various objects in life. Operator reload format access modification permission + Data Type + keyword (operator) + operator + (form parameter table) {function body;} operator reload instance
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace ConsoleApplication14 {class Program {public static void Main (string [] args) {Vector vect1, vect2, vect3; vect1 = new Vector (3.0, 3.0, 1.0 ); // call the operator function vect2 = new Vector (2.0,-4.0,-4.0); vect3 = vect1 + vect2; // implement the operator to overload the Console. writeLine (vect1.ToString (); Console. writeLine (vect2.ToString (); Console. writeLine (vect3.ToString ();} class Vector {private double x, y, z; public double X {get {return x;} set {y = value ;}} public double Y {get {return y;} set {y = value ;}} public double Z {get {return z;} set {z = value ;}} public Vector () {x = 0; y = 0; z = 0;} public Vector (Vector rhs) {x = rhs. x; y = rhs. y; z = rhs. z;} public Vector (double x, double y, double z) {this. x = x; this. y = y; this. z = z;} public override string ToString () {return "X coordinate:" + x + "Y coordinate:" + y + "Y coordinate: "+ z;} public static Vector operator + (Vector lhs, Vector rhs) // declare operator overload {Vector result = new Vector (lhs); result. x + = rhs. x; result. y + = rhs. y; result. z + = rhs. z; return result ;}}}}
Different operators have different requirements for overloading.