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