250x250
Notice
Recent Posts
Recent Comments
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

minjea.dev의 코딩블로그

[c#] 오버로드 (오버라이딩 아님주의!) 그리고 여러 기능들 본문

코딩강좌/c#

[c#] 오버로드 (오버라이딩 아님주의!) 그리고 여러 기능들

minjea.dev 2022. 4. 17. 12:00
728x90

오버라이드는 완벽히 반환타입과, 매개변수의 숫자 등이 동일한 메서드를 재정의할때 사용한다면, 오버로드(overload)는 매개변수의 수나, 매개변수들의 타입만 다르게 재정의하는것을 뜻합니다.

메서드 오버로드

메서드는 매개변수의 수나, 매개변수들 각각의 타입이 다른 여러가지 동일한 이름의 메서드를 여러개 정의할수 있습니다. 다음과 같이 말이죠

class Math {
    public int returnBig(int value1, int value2) {
        return value1>=value2?value1:value2;
    }
    
    public double returnBig(double value1, double value2) {
        return value1>=value2?value1:value2;
    }
    
    public decimal returnBig(decimal value1, decimal value2) {
        return value1>=value2?value1:value2;
    }
}

이러면 메서드를 여러개 만들어 사용이 가능합니다

 

연산자 오버로드

c#에서는 연산자도 재정의가 가능합니다. 예를 들어 +, -, /, %등을 재정의를 할수도 있습니다. 그럼 여기선, +와 -를 재정의해보도록 하겠습니다. 저번에 만든 Human 클래스를 조금 이용해서 말이죠. 다음과 같이 Human 클래스를 정의해주세요

class Human {
    public string name;
    public int age;
    public string gender;
    
    public Human(string name, int age, string gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

이 클래스에 +와 -연산자를 재정의할 예정인데, 다음과 같이 코드를 작성하면 연산자를 재정의할수 있습니다

public static [형(타입)] operator 연산자 (타입 변수명1, 타입 변수명2) {
    // code
}

그렇다면 이걸 그대로 적용해서 먼저 + 연산자를 재정의해보겠습니다. 여기서는 나이를 더해 리턴하므로, 리턴 타입이 int 형입니다. 새로운 객체를 생성하거나 다른 타입을 리턴하는 연산자를 추가하시려는 경우엔, 그 타입을 리턴타입으로 명시하시면 됩니다.

class Human {
    public string name;
    public int age;
    public string gender;
    
    public Human(string name, int age, string gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    
    public static int operator +(Human human1, Human human2) {
        return human1.age+human2.age;
    }
}

그럼 이걸 어떻게 사용할까요? 다음과 같이 사용하시면 됩니다.

Human woojin = new Human("우진",100,"Men");
Human gate = new Human("빌게이츠",65,"Men");
Console.WriteLine(woojin+gate); // 165

결과를 보면 잘 작동하는 것을 볼수 있습니다. 이 방식으로 - 연산자도 정의해보겠습니다.

class Human {
    public string name;
    public int age;
    public string gender;
    
    public Human(string name, int age, string gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    
    public static int operator +(Human human1, Human human2) {
        return human1.age+human2.age;
    }
    
    public static int operator -(Human human1, Human human2) {
        return human1.age-human2.age;
    }
}

이것도 아래와 같이 사용하면 값이 제대로 나오는 것을 볼 수 있습니다

Human woojin = new Human("우진",100,"Men");
Human gate = new Human("빌게이츠",65,"Men");
Console.WriteLine(woojin-gate); // 35

 

형변환 (클래스)

이 글은 네이버 블로그에서 한 글을 보고 참고하여 작성되었습니다. (글 작성자님 감사합니다.)

 

형변환을 재정의하는 건, 가끔 유용할때가 존재합니다. 통화를 계산하는것처럼, 가끔 이런 형변환이 필요할수도 있으니, 알고 넘어가시는게 좋을것 같습니다. 여기서도 원화와 달러를 환율에 따라 계산합니다. (작성일기준 반올림해서 1달러당 1,229원이어서, 이 환율을 적용해서 코드를 작성했습니다.)

 

클래스 형변환에도 암시적 형변환과, 명시적 형변환이 존재하는데, 이를 두개를 각각 다르게 정의할수 있습니다. 암시적 형변환은 implicit 키워드로, 명시적 형변환은 explicit 키워드로 정의가 가능합니다. 일단 다음과 같이 원화 클래스와 달러화 클래스를 정의하시기 바랍니다.

 

암시적 형변환은 다음과 같이 정의할수 있습니다.

static public implicit operator [변환될타입]([클래스타입] 변수명) {
    // 코드
}

그럼 다음 형식을 이용하여 원화 클래스와 달러화 클래스에 각각 암시적 형변환 기능을 추가해보겠습니다.

public class Won {
    public decimal money;
    
    public Won(decimal money) {
        this.money = money;
    }
}

public class Dollar {
    public decimal money;
    
    public Dollar(decimal money) {
        this.money = money;
    }
}

이렇게 선언한 클래스에 형변환 코드를 추가해보겠습니다. 먼저 암시적(implicit) 형변환을 추가해보겠습니다.

public class Won
{
    public decimal money;

    public Won(decimal money)
    {
        this.money = money;
    }

    static public implicit operator Dollar(Won won)
    {
        return new Dollar(won.money / 1229);
    }
}

public class Dollar
{
    public decimal money;

    public Dollar(decimal money)
    {
        this.money = money;
    }

    static public implicit operator Won(Dollar dollar)
    {
        return new Won(dollar.money * 1229);
    }
}

이렇게하면 원화 클래스와 달러화 클래스의 인스턴스끼리는 각각 암시적 형변환이 가능해지게 됩니다. 다음 코드처럼 말이죠

Won won = new Won(12290);
Dollar won_to_dollar = won; // 원화를 달러화로 암시적 형변환
Console.WriteLine(won_to_dollar.money); // 10 (달러화)

Dollar dollar = new Dollar(100);
Won dollar_to_won = dollar; // 달러를 원화로 암시적 형변환
Console.WriteLine(dollar_to_won.money); // 122900 (원화)

 

그러면 명시적 형변환은 어떻게 정의할까요? 다음과 같이 가능합니다.

static public explicit operator [변환될타입]([클래스타입] 변수명) {
    // 코드
}

그럼 이걸 적용하여 각 클래스에 명시적 형변환 기능을 추가해보겠습니다.

public class Won
{
    public decimal money;

    public Won(decimal money)
    {
        this.money = money;
    }

    static public implicit operator Dollar(Won won)
    {
        return new Dollar(won.money / 1229);
    }
    
    static public explicit operator Dollar(Won won)
    {
        return new Dollar(won.money / 1229);
    }
}

public class Dollar
{
    public decimal money;

    public Dollar(decimal money)
    {
        this.money = money;
    }

    static public implicit operator Won(Dollar dollar)
    {
        return new Won(dollar.money * 1229);
    }
    
    static public explicit operator Won(Dollar dollar)
    {
        return new Won(dollar.money * 1229);
    }
}

이렇게 코드를 추가하면 다음과 같이 명시적인 형변환이 가능합니다.

Won won = new Won(12290);
Dollar won_to_dollar = (Dollar)won; // 원화를 달러화로 명시적 형변환
Console.WriteLine(won_to_dollar.money); // 10 (달러화)

Dollar dollar = new Dollar(100);
Won dollar_to_won = (Won)dollar; // 달러를 원화로 명시적 형변환
Console.WriteLine(dollar_to_won.money); // 122900 (원화)

이렇게 암시적 형변환과 명시적 형변환을 이제 구현하실수 있게 되셨습니다. 필요할때 암시적 형변환과 명시적 형변환중 원하는 기능을 필요할때 추가해 사용하시면 될듯 합니다.

728x90