========================================================== Operator overload
------------------------------------------------------------------------- Vector. CS
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading. tasks; namespace consoleapplication4 {public struct vector // The Structure and class are similar to {public int x, y, z; Public vector (int x, int y, int Z) // constructor {This. X = x; this. y = y; this. z = z;} public vector (vector v) // constructor {This. X = v. x; this. y = v. y; this. z = v. z;} public override string tostring () // reload the tostring method {return string. format ("X: {0}; Y: {1}; Z: {2}", x, y, z );} // overload operator // The first parameter is on the left of the operator, and the second parameter is on the right of the operator. // +-*/is the same public static vector operator * (vector LHS, vector RHs) {vector v = new vector (LHS); V. x * = RHS. x; V. y * = RHS. y; V. z * = RHS. z; return v ;}}}
------------------------------------------------------------------------- Main program
Vector V1 = new vector (1, 2, 3); vector v2 = new vector (3, 2, 1); console. writeline (V1 * V2 ). tostring (); // output X: 3; Y: 4; Z: 3 console. readkey ();
========================================================== Comparison operator overload
------------------------------------------------------------------------- Vector. CS
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading. tasks; namespace consoleapplication4 {public struct vector // The Structure and class are similar to {public int x, y, z; Public vector (int x, int y, int Z) // constructor {This. X = x; this. y = y; this. z = z;} public vector (vector v) // constructor {This. X = v. x; this. y = v. y; this. z = v. z;} public override string tostring () // reload the tostring method {Return string. format ("X: {0}; Y: {1}; Z: {2}", x, y, z );} // reload the comparison operator // = and! = Need to appear in pairs //> and <need to appear in pairs //> = and <= need to appear in pairs public static bool operator = (vector LHS, vector RHs) {vector v = new vector (LHS); If (v. X = RHS. X & v. y = RHS. Y & v. z = RHS. z) {return true;} else {return false;} // reload the comparison operator public static bool Operator! = (Vector LHS, vector RHs) {return! (LHS = RHs );}}}
------------------------------------------------------------------------- Main program
Vector v1 = new Vector(1, 2, 3); Vector v2 = new Vector(1, 2, 3); Console.WriteLine(v1 == v2);//true Console.ReadKey();
650) This. width = 650; "Title =" spximage47.jpg "src =" http://s3.51cto.com/wyfs02/M00/43/6B/wKioL1PaTgSi2TABAAKoj1NHZUM361.jpg "alt =" wkiol1patgsi2tabaakoj1nhzum361.jpg "/>
This article from the "programmer's home" blog, please be sure to keep this source http://962410314.blog.51cto.com/7563109/1533446