How to: Use the operator to overload to create a plural class

Source: Internet
Author: User

This example shows how to create a plural class that defines the plural addition using the operator overload.Complex. This program uses the tostring method to overload the display of the imaginary and real parts of the number and the addition result.

1 public struct Complex
2 {
3 Public int real;
4 Public int imaginary;
5
6 Public complex (INT real, int imaginary) // Constructor
7 {
8 This. Real = real;
9 This. Imaginary = imaginary;
10}
11
12 // declare which operator to overload (+ ),
13 // the types that can be added (two complex objects ),
14 // and the return type (complex ):
15 public static complex operator + (complex C1, complex C2)
16 {
17 return new complex (c1.real + c2.real, c1.imaginary + c2.imaginary );
18}
19
20 // override the tostring () method to display a complex number in the traditional format:
21 public override string tostring ()
22 {
23 return (system. String. Format ("{0} + {1} I", real, imaginary ));
24}
25}
26
27 class testcomplex
28 {
29 static void main ()
30 {
31 complex num1 = new complex (2, 3 );
32 complex num2 = new complex (3, 4 );
33
34 // Add two complex objects through the overloaded plus OPERATOR:
35 complex sum = num1 + num2;
36
37 // print the numbers and the sum using the overriden tostring method:
38 system. Console. writeline ("first complex number: {0}", num1 );
39 system. Console. writeline ("second complex number: {0}", num2 );
40 system. Console. writeline ("the sum of the two numbers: {0}", sum );
41}
42}

Output:

First complex number:  2 + 3iSecond complex number: 3 + 4iThe sum of the two numbers: 5 + 7i

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.