C # operator overloading

Source: Internet
Author: User
You can redefine or reload the built-in operators in C #. As a result, programmers can also use operators of user-defined types. Overloaded operators are functions with special names that are defined by the operator of the keyword followed by the operator. As with other functions, overloaded operators have return types and parameter lists.

For example, consider the following function:

public static box operator+ (Box B, box C) {   box box = new box ();   Box.length = B.length + c.length;    Box.breadth = B.breadth + c.breadth;    Box.height = B.height + c.height;    return box;}

The above function implements the addition operator (+) for the user-defined class Box. It adds the attributes of the two box objects and returns the added box object.

Implementation of operator overloading

The following program demonstrates the complete implementation:

Using System;namespace operatorovlapplication{class Box {private double length;     Length privatedouble breadth;      width private double height;      Height public double Getvolume () {return length * breadth * height;      public void SetLength (double len) {length = Len;      } public void Setbreadth (double bre) {breadth = bre;      } public void SetHeight (double hei) {height = hei;         }//Overload + operator to add two box objects public static box operator+ (Box B, box C) {Box box = new box ();         Box.length = B.length + c.length;         Box.breadth = B.breadth + c.breadth;         Box.height = B.height + c.height;       return box;          }} class Tester {static void Main (string[] args) {Box Box1 = new box ();          Statement Box1, type box box Box2 = new box ();          Statement Box2, type box box Box3 = new box (); //Declaration Box3, type Box double volume = 0.0;          Volume//Box1 detailed box1.setlength (6.0);          Box1.setbreadth (7.0);          Box1.setheight (5.0);          Box2 detailed box2.setlength (12.0);          Box2.setbreadth (13.0);          Box2.setheight (10.0);          Box1 Volume volume = Box1.getvolume ();          Console.WriteLine ("Volume of Box1: {0}", volume);          Box2 Volume volume = Box2.getvolume ();          Console.WriteLine ("Volume of Box2: {0}", volume);          Add two objects Box3 = Box1 + Box2;          Box3 Volume volume = Box3.getvolume ();          Console.WriteLine ("Volume of Box3: {0}", volume);       Console.readkey (); }    } }

When the above code is compiled and executed, it produces the following results:

Volume of Box1: Box2 Volume: 1560 Box3 Volume: 5400

Overloaded and non-overloaded operators

The following table describes the capabilities of operator overloading in C #:

Operator Describe
+, -, !, ~, ++, -- These unary operators have only one operand and can be overloaded.
+, -, *, /, % These two-tuple operators have two operands and can be overloaded.
= =,! =, <, <=;, >= These comparison operators can be overloaded
&&, | | These conditional logical operators cannot be overloaded directly.
+=, -=, *=, /=, %= These assignment operators cannot be overloaded.
=,.,?:,->, new, is, sizeof, typeof These operators cannot be overloaded.

Instance

For the above discussion, let's extend the above example, overloading more operators:

Using System;namespace operatorovlapplication{class Box {private double length;     Length privatedouble breadth;      width private double height;       Height public double Getvolume () {return length * breadth * height;      public void SetLength (double len) {length = Len;      } public void Setbreadth (double bre) {breadth = bre;      } public void SetHeight (double hei) {height = hei;          }//Overload + operator to add two box objects public static box operator+ (Box B, box C) {Box box = Newbox ();          Box.length = B.length + c.length;          Box.breadth = B.breadth + c.breadth;          Box.height = B.height + c.height;      return box;         } public static bool operator = = (Box lhs, box RHS) {BOOL status = FALSE; if (lhs.length = = Rhs.length && Lhs.height = = Rhs.height && lhs.breadth = RHS.breadth) {status = TRUE;      } return status;          public static bool Operator! = (box lhs, box RHS) {BOOL status = FALSE;              if (lhs.length! = Rhs.length | | Lhs.height! = Rhs.height | | lhs.breadth! = rhs.breadth) {          Status = TRUE;      } return status;          } public static bool operator < (box lhs, box RHS) {bool status =false;           if (Lhs.length < rhs.length && Lhs.height < rhs.height && Lhs.breadth < Rhs.breadth)          {status = True;      } return status;          } public static bool operator > (Box lhs, box RHS) {bool status =false;           if (Lhs.length > Rhs.length && lhs.height > Rhs.height && lhs.breadth > Rhs.breadth)          {status = True;      } return status; } Public Static bool operator <= (Box lhs, box RHS) {BOOL status = FALSE; if (lhs.length <= rhs.length && lhs.height <= rhs.height && lhs.breadth <= Rhs.brea          DTH) {status = TRUE;      } return status;            } public static bool operator >= (Box lhs, box RHS) {BOOL status = FALSE; if (lhs.length >= rhs.length && lhs.height >= rhs.height && lhs.breadth >= Rhs.breadt          h) {status = TRUE;      } return status; } public override string ToString () {Returnstring.format ("({0}, {1}, {2})", length, breadth, heigh      T);             }} class Tester {static void Main (string[] args) {Box Box1 = new box ();             Statement Box1, type box box Box2 = new box ();              Statement Box2, type box box Box3 = new box (); Statement Box3, type box box Box4 = new box ();       Double volume = 0.0;            Volume//Box1 detailed box1.setlength (6.0);            Box1.setbreadth (7.0);            Box1.setheight (5.0);            Box2 detailed box2.setlength (12.0);            Box2.setbreadth (13.0);           Box2.setheight (10.0);            Use the overloaded ToString () to display two boxes of Console.WriteLine ("Box1: {0}", box1.tostring ());                    Console.WriteLine ("Box2: {0}", box2.tostring ());            Box1 Volume volume = Box1.getvolume ();            Console.WriteLine ("Volume of Box1: {0}", volume);            Box2 Volume volume = Box2.getvolume ();            Console.WriteLine ("Volume of Box2: {0}", volume);            Add two objects box3= Box1 + Box2;            Console.WriteLine ("Box3: {0}", box3.tostring ());            Box3 Volume volume =box3.getvolume ();            Console.WriteLine ("Volume of Box3: {0}", volume); Comparing the boxes IF (Box1 >box2) Console.WriteLine ("Box1 Greater than Box2");            else Console.WriteLine ("Box1 is not much more than Box2");            if (Box1 <box2) Console.WriteLine ("Box1 Less than Box2");            else Console.WriteLine ("Box1 not less than Box2");            if (box1>= Box2) Console.WriteLine ("Box1 is greater than or equal to Box2");            else Console.WriteLine ("Box1 is not greater than or equal to Box2");            if (Box1 <= Box2) Console.WriteLine ("Box1 less than equals Box2");            else Console.WriteLine ("Box1 is not less than or equal to Box2");            if (Box1! = Box2) Console.WriteLine ("Box1 Not equal to Box2");            else Console.WriteLine ("Box1 equals Box2");            Box4 = Box3;            if (Box3 = = Box4) Console.WriteLine ("Box3 equals Box4");            else Console.WriteLine ("Box3 Not equal to Box4");          Console.readkey (); }        }    }

When the above code is compiled and executed, it produces the following results:

Box1: (6, 7, 5) Box2: (A) Box1 Volume: Box2 Volume: 1560 Box3: () Box3 Volume: 5400 Box1 less than Box2 Box1 smaller than Bo X2 Box1 not greater than or equal to Box2 Box1 less than equals Box2 Box1 not equal to Box2 Box3 equals Box4

The above is the contents of C # operator overloading, please pay more attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.