C # Operator Overloading

Source: Internet
Author: User

Requirements for operator overloading:

 

The reload instance is:

The classes to be overloaded are defined as follows:

 1 class LimitedInt 2     { 3         const int MaxValue = 100; 4         const int MinValue = 0; 5  6         public static LimitedInt operator -(LimitedInt x) 7         { 8             LimitedInt li = new LimitedInt(); 9             li.TheValue = -x.TheValue;10             return li;11         }12         public static LimitedInt operator -(LimitedInt x,double y)13         {14             LimitedInt li = new LimitedInt();15             li.TheValue = x.TheValue - (int)y;16             return li;17         }18 19         private int _TheValue = 0;20         public int TheValue21         {22             get 23             {24                 return _TheValue;25             }26             set27             {28                 _TheValue = value;29             }30         }31 }

It can be seen that the first overload operator is a single object operator, with a-sign

The second operator is A-number, but a binary operator.

In this case, you can make the following calls:

 1 class Program 2     { 3         static void Main(string[] args) 4         { 5             LimitedInt x = new LimitedInt(); 6             x.TheValue = 13; 7  8             double y = 7; 9 10             LimitedInt li = new LimitedInt();11 12             li =x-y;13 14             Console.WriteLine("{0}",li.TheValue);15 16             li = -x;17 18             Console.WriteLine("{0}",li.TheValue);19 20             Console.ReadKey();21         }22     }

The output is 6 and-13. The operation is correct.

C # Operator Overloading

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.