Add + operator for Complex type : operator overload Binary Plus Subtract « Operator Overload « C# / CSharp Tutorial

Home
C# / CSharp Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statement
5.String
6.struct
7.Class
8.Operator Overload
9.delegate
10.Attribute
11.Data Structure
12.Assembly
13.Date Time
14.Development
15.File Directory Stream
16.Preprocessing Directives
17.Regular Expression
18.Generic
19.Reflection
20.Thread
21.I18N Internationalization
22.LINQ
23.GUI Windows Forms
24.Windows Presentation Foundation
25.Windows Communication Foundation
26.Workflow
27.2D
28.Design Patterns
29.Windows
30.XML
31.XML LINQ
32.ADO.Net
33.Network
34.Directory Services
35.Security
36.unsafe
C# / C Sharp
C# / C Sharp by API
C# / CSharp Open Source
C# / CSharp Tutorial » Operator Overload » operator overload Binary Plus Subtract 
8.9.1.Add + operator for Complex type
using System;

public struct Complex
{
    public Complexdouble real, double imaginary ) {
        this.real = real;
        this.imaginary = imaginary;
    }

    static public Complex AddComplex lhs, Complex rhs ) {
        return new Complexlhs.real + rhs.real, lhs.imaginary  + rhs.imaginary );
    }

    static public Complex AddComplex lhs, double rhs ) {

        return new Complexrhs + lhs.real, lhs.imaginary );
    }

    public override string ToString() {
        return String.Format"({0}, {1})", real, imaginary );
    }

    static public Complex operator+Complex lhs, Complex rhs ) {
        return Addlhs, rhs );
    }

    static public Complex operator+double lhs, Complex rhs ) {
        return Addrhs, lhs );
    }

    static public Complex operator+Complex lhs, double rhs ) {
        return Addlhs, rhs );
    }

    private double real;
    private double imaginary;
}

public class MainClass
{
    static void Main() {
        Complex cpx1 = new Complex1.03.0 );
        Complex cpx2 = new Complex1.02.0 );

        Complex cpx3 = cpx1 + cpx2;
        Complex cpx4 = 20.0 + cpx1;
        Complex cpx5 = cpx1 + 25.0;

        Console.WriteLine"cpx1 == {0}", cpx1 );
        Console.WriteLine"cpx2 == {0}", cpx2 );
        Console.WriteLine"cpx3 == {0}", cpx3 );
        Console.WriteLine"cpx4 == {0}", cpx4 );
        Console.WriteLine"cpx5 == {0}", cpx5 );
    }
}
cpx1 == (1, 3)
cpx2 == (1, 2)
cpx3 == (2, 5)
cpx4 == (21, 3)
cpx5 == (26, 3)
8.9.operator overload Binary Plus Subtract
8.9.1.Add + operator for Complex type
8.9.2.Operator overloading: +, -
8.9.3.An operator overloading: binary + and -
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.