노트

[C#] 연산자 오버로딩(operator) 본문

ㄱㅂ/C#

[C#] 연산자 오버로딩(operator)

늅뎁 2021. 5. 26. 15:09
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class OverloadingTest
{
    public int A { get; set; }
    public int B { get; set; }
 
    public OverloadingTest(int \_a, int \_b)
    {
        this.A = \_a;
        this.B = \_b;
    }
 
    public static OverloadingTest operator +(OverloadingTest o1, OverloadingTest o2)
    {
        return new OverloadingTest(o1.A + o1.B, o2.A + o2.B);
    }
 
    public static OverloadingTest operator -(OverloadingTest o1, OverloadingTest o2)
        => new OverloadingTest(o1.A, o2.B);
 
    public override string ToString()
    {
        return string.Format("A : {0}, B : {1}", A, B);
    }
}
 
class Program
{
    static void Main(string\[\] args)
    {
        OverloadingTest over1 = new OverloadingTest(12);
        OverloadingTest over2 = new OverloadingTest(1020);
 
 
        Console.WriteLine((over1 + over2).ToString()); // output - A : 3, B : 30
 
        Console.WriteLine((over1 - over2).ToString()); // output - A : 1, B : 20
    }
}
cs

 

미리정의된 연산자(+,-,* 등등)를 오버로딩 할 수있다.

즉 해당 연산자에 대해 의미를 다시 부여하는 것이다.

 

 

출처 : https://docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/operators/operator-overloading

반응형