Learning C # advanced programming together 3 -- Operator Overloading,

Source: Internet
Author: User

Learning C # advanced programming together 3 -- Operator Overloading,

Operator. C ++ developers should be familiar with this concept, but it is brand new to Java and VB developers.

For some calculation between values, if you use a method to specify the operation rules, it will be cumbersome, then you can use the operator overload.

Example:

Matrix a, B, c; // defines a Matrix object

Marix d = c * (a + B );

If you use a language that does not support Operator overloading, you must define a method and call the method for calculation:

Marix d = c. Muliply (a. Add (B ));

The results are not intuitive.

  

Operator Overloading is often used in mathematical or physical modeling (such as coordinates, vectors, matrices, and function operations ). There are also proportions and financial aspects .. Of course, if you want to calculate a date, such as multiplying two DateTime values, no one will block you, although it has no meaning in concept, haha.

 

In fact, we used to reload operators when writing code. Although we didn't define overload operators, C # is implemented by default.

int myInt=3;uint myUint=2;double myDouble=13.2;long myLong=myInt+myUint;double myDouble=myDouble+myInt;double myDouble2=myInt+myDouble;

The "+" operator accepts two parameters, and then searches for the reload method of the most matching Operator Based on the parameters.

The preceding long myLong = myInt + myUint; and double myDouble2 = myInt + myDouble; call overload of different versions.

In C #, the compiler automatically matches the most suitable overload method. For example, for double and int data, the "+" operator does not include the overload of this composite parameter, therefore, the compiler considers that the most matched "+" overload is the addition of two double types, and it is not surprising that the resulting number is of the double type.

 

So what will happen to the custom type? In this way, you have to define the overload of the operator.

Defines a Vector structure to represent a three-dimensional mathematical coordinate (x, y, z)

Struct Vector {private double x, y, z; public Vector (double x, double y, double z) {this. x = x; this. y = y; this. z = z;} public Vector (Vector vec) {this. x = vec. x; this. y = vec. y; this. z = vec. z;} public override string ToString () {return "(" + x + "," + y + "," + z + ")";} // + operator overload public static Vector operator + (Vector lhs, Vector rhs) {Vector result = new Vector (); result. x = lhs. x + rhs. x; result. y = lhs. y + rhs. y; result. z = lhs. z + rhs. z; return result; // returns the value after adding two three-dimensional coordinates }}
  

Static void Main (string [] args)
{
// Define a three-dimensional coordinate object
Vector vec1 = new Vector (1, 0,-2 );
Vector vec2 = new Vector (2,-1, 5 );
Vector vec3 = vec1 + vec2;

 

Console. WriteLine (vec1.ToString (); // output (1, 0,-2)
Console. WriteLine (vec2.ToString (); // output (2,-1, 5)
Console. WriteLine (vec3.ToString (); // output (3,-1, 3)
Console. ReadLine ();
}

 

Of course, you can also define more overload operations, such as addition, subtraction, and multiplication. You can also multiply a scalar by a vector, such as 2 * (, 3)

Public static Vector operator * (double lhs, Vector rhs)
{
Return new Vector (lhs * rhs. x, lhs * rhs. y, lhs * rhs. z );
}

This overload is called for both 2.0 * (, 3) and 2 * (, 3. However, for (1, 2, 3) * 2, you must reload another method.

Public static Vector operator * (Vector lhs, double rhs)
{
Return rhs * lhs;
}

Here, there is no need to re-calculate the process as in the previous method and directly reuse the above Code .. This article describes the concise idea of the code and improves the maintainability of the Code.

I believe that it is not difficult to write a vector multiplication statement.

 

Of course, there are also reloads of comparison characters, including the following three pairs:

= And! =

> And <

>=And <=

In fact, the operation of the overload method is the same. Change the "+" operator in the previous example to a comparison operator.

Public static bool operator = (Vector lhs, Vector rhs)
{
Return ???
}

 

I wrote it for an hour at, so hurry to bed!

Next content: common system pre-fabricated numeric type conversion (for example, float is converted to double). What is the conversion of user-defined types?

Next description,Forced conversion of user-defined types

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.