C # Syntax Basics (ii)--operator overloading

Source: Internet
Author: User

C # allows user-defined types to overload operators by defining static member functions using the operator keyword

Let's look at an example:

 Public classcomplexnumber{Private intReal; Private intimaginary; //Constructors     PublicComplexNumber (intRinti) {real=R; Imaginary=i; }    //overloads the ToString method, which is used to display ComplexNumber     Public Override stringToString () {if(Imaginary >=0)            return(System.String.Format ("{0}+{1}i", real, imaginary)); Else            return(System.String.Format ("{0}-{1}i", real, imaginary)); }}

We need +,-to add or subtract two imaginary numbers, using the following method overload +,-operator

//Overloaded + operators Public StaticComplexNumberoperator+(ComplexNumber lhs,complexnumber rhs) {return NewComplexNumber (Lhs.real+rhs.real,lhs.imaginary+rhs.imaginary);}//Overloaded-Operator Public StaticComplexNumberoperator-(ComplexNumber lhs,complexnumber rhs) {return NewComplexNumber (Lhs.real-rhs.real,lhs.imaginary-rhs.imaginary);}

Operator overloading is declared in the same way as methods, but the operator keyword tells the compiler that it is actually an operator overload.

In this example

public static ComplexNumber operator+(ComplexNumber lhs,complexnumber RHS)

The overloaded operator "+" that represents the global static return value is the ComplexNumber type, the input parameter is a two-complexnumber variable, the return value is still complexnumber,

The action returned is to call the constructor in the ComplexNumber class and the ToString method.

public static implicit operator ComplexNumber (double D)

Where implicit represents the stealth type conversion, and D is converted from double to complexnumber type.

Public double D (get;set;)

is a forced type conversion form, meaning to cast to double type

C # Syntax Basics (ii)--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.