The concrete operation principle of overloaded auto-decrement operator in C #----The essence of C # self-increment operator overloading from the perspective of C + + programmer

Source: Internet
Author: User

Look at the operator overloads of C #, and find that they are not the same as C + +. Just been in the C # self-increment operator pit, now to share.

First define a class

    class A    {        publicint  i;          Public A (int  i)        {            = i;        }  Public Static operator + + +(a A)        {            returnnew A (+);        }    } 

Main function

    class program    {        staticvoid Main (string[] args)        {            new A (10 );            Console.WriteLine (V.I);            V+ +;            Console.WriteLine (V.I);                        Console.readkey ();        }    }

To tell you the truth, the promise I predicted at first was totally wrong.

I thought the value of V.I is still 10, that is, printing two 10

Results

The real print results are:

This is totally beyond the expectation of my C + + programmer.

because when I call v++, I think I see the specific overloaded method [ public static A operator + +(a A) ] Here's a sentence return new A (+); it is completely invisible that there is a half-penny relationship with V.

........

Thought for a long time the original is this:

Suppose there is a static method in Class A:

 Public Static a F (a a) {    returnnew A (+);}

So

v++ This can be equivalent to the Write V = a.f (v);

That is, the method that calls the operator with V as a parameter, then assigns the return value to V;

That's it, the value of V is finally replaced, so the C # operator overload can be thought of as an illusion.

That is why the overloaded + + operator return type must be the reason for the containing type or the type derived from the containing type.

The concrete operation principle of overloaded auto-decrement operator in C #----The essence of C # self-increment operator overloading from the perspective of C + + programmer

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.