다음을 통해 공유


방법: 연산자 오버로딩을 사용하여 복소수 클래스 만들기(C# 프로그래밍 가이드)

업데이트: 2007년 11월

다음 예제에서는 연산자 오버로드를 사용하여 복잡한 더하기를 정의하는 복잡한 수 클래스 Complex를 만드는 방법을 보여 줍니다. 프로그램에서는 ToString 메서드를 재정의하여 수의 실제 부분과 가상 부분 및 더하기 결과를 표시합니다.

예제

public struct Complex
{
    public int real;
    public int imaginary;

    public Complex(int real, int imaginary)  //constructor
    {
        this.real = real;
        this.imaginary = imaginary;
    }

    // Declare which operator to overload (+),
    // the types that can be added (two Complex objects),
    // and the return type (Complex):
    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
    }

    // Override the ToString() method to display a complex number in the traditional format:
    public override string ToString()
    {
        return (System.String.Format("{0} + {1}radius", real, imaginary));
    }
}

class TestComplex
{
    static void Main()
    {
        Complex num1 = new Complex(2, 3);
        Complex num2 = new Complex(3, 4);

        // Add two Complex objects through the overloaded plus operator:
        Complex sum = num1 + num2;

        // Print the numbers and the sum using the overriden ToString method:
        System.Console.WriteLine("First complex number:  {0}", num1);
        System.Console.WriteLine("Second complex number: {0}", num2);
        System.Console.WriteLine("The sum of the two numbers: {0}", sum);

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    First complex number:  2 + 3i
    Second complex number: 3 + 4i
    The sum of the two numbers: 5 + 7i
*/

참고 항목

개념

C# 프로그래밍 가이드

참조

C# 연산자

operator(C# 참조)

기타 리소스

Why are overloaded operators always static in C#?