Re-reading C # Operator Overloading in Advanced Programming

Source: Internet
Author: User

We often perform arithmetic operations. Comparison operations are actually an overloaded operator, but they only correspond to common data types. If we want to perform operations on the class and struct, what will happen? The compiler does not know. We can only reload this operation.
Demo:

Using System;
Using System. Collections. Generic;
Using System. text;

Namespace Constructordemo
{
// A binary operator must be of the include type.
// A parameter must be a class
// -============================================== ====================
Class Reloadalg
{
Static   Void Main ( String [] ARGs)
{
CLSA cls1 =   New CLSA ( 10 , 50 );
Clsb cls2 =   New Clsb ( 50 , 70 );
CLSA result = Cls1 + Cls2;
Console. writeline (result. inuma );
Console. writeline (result. jnuma );
}
}

Class CLSA
{
Private   Int Inuma;

Public   Int Inuma
{
Get   {ReturnInuma ;}
Set   {Inuma=Value ;}
}
Private   Int Jnuma;

Public   Int Jnuma
{
Get   {ReturnJnuma ;}
Set   {Jnuma=Value ;}
}

Public CLSA ( Int I, Int J)
{
This. Inuma=I;
This. Jnuma=J;
}
}
Class Clsb
{
Private   Int Inumb;

Public   Int Inumb
{
Get   {ReturnInumb ;}
Set   {Inumb=Value ;}
}
Private   Int Jnumb;

Public   Int Jnumb
{
Get   {ReturnJnumb ;}
Set   {Jnumb=Value ;}
}

Public Clsb ( Int I, Int J)
{
This. Inumb=I;
This. Jnumb=J;
}

// Format: public static [returntype] OPERATOR [Operator] (XX, YY)
Public   Static CLSA Operator   + (CLSA, clsb) // A parameter must be a class
{
CLSA clsresult =   New CLSA ( 0 , 0 );
Clsresult. inuma = CLSA. inuma + Clsb. inumb;
Clsresult. jnuma = CLSA. jnuma + Clsb. jnumb;
Return Clsresult;
}
}
}

In addition

1. When the comparison operator number is reloaded, it must be reloaded in pairs (= ,! =) (>,<) (>=, <=)
2. The comparison operator must return a value of the bool type.

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.