2016-12-14 3 views
0

부모 클래스를 상속하는 다른 클래스 하위 클래스가 있습니다.연산자 오버로딩 메서드 재정의

부모님 안에 연산자 오버로딩 메서드가 있습니다. 하위 개체에서도 작업을 수행하고 싶습니다. 그러나 나는 이것을하는 방법을 모르겠다.

public class Parent 
{ 
    public int age; 
    public static Parent operator + (Parent a, Parent b) 
    { 
    Parent c = new Parent(); 
    c.age = a.age + b.age; 
    return c; 
    } 
} 

public class Child : Parent 
{ 
    //other fields... 
} 

나는 생각할 수있는 유일한 방법은 아이에게 똑같은 방법과 논리를 복사하는 것입니다. 그러나 나는 코드가 중복이기 때문에 그것은 좋은 방법이 아니다 믿습니다 : (코드가 매우 긴 특히 경우) 내가 캐스팅하려고 노력

public class Child : Parent 
{ 
    public static Child operator + (Child a, Child b) 
    { 
    Child c = new Child(); 
    c.age = a.age + b.age; 
    return c; 
    } 
} 

하지만 런타임에 실패

public class Child : Parent 
{ 
    public static Child operator + (Child a, Child b) 
    { 
    return (Child)((Parent)a + (Parent)b); 
    } 
} 

가 있는가 이것을 달성하는 더 좋은 방법은? 고맙습니다.

+0

당신이 부모 A = 새로운 아이 "와 같은 하위 클래스 객체를 시작하는 부모의 유형을 사용하여 시도해 봤어 호출하는 보호 생성자에 논리를 이동하는 것(); " –

+0

내가 부모를 사용하여 시작하는 경우에도 부모 (부모)와 부모 (부모)를 다시 자식으로 변환하려면 어떻게해야합니까? – user3545752

+0

사이드 노트 :이 문제에 직면했을 때 아무도 부모 + 자녀로부터 기대할 것을 이해할 수 없으므로 코드를 읽을 수 없다는 것을 의미합니다. 이 시점에서 빌더 방법 또는 다른 뭔가가 더 나은 옵션이 될 수 있습니다. –

답변

1

궁극적으로 Child 개체를 만들어야하지만 논리를 보호 된 메서드로 옮길 수 있습니다.

public class Parent 
{ 
    public int age; 
    public static Parent operator + (Parent a, Parent b) 
    { 
    Parent c = new Parent(); 
    AddImplementation(a, b, c); 
    return c; 
    } 

    protected static void AddImplementation(Parent a, Parent b, Parent sum) 
    { 
    sum.age = a.age + b.age; 
    } 
} 

public class Child : Parent 
{ 
    public static Child operator + (Child a, Child b) 
    { 
    Child c = new Child(); 
    AddImplementation(a, b, c); 
    return c; 
    } 
} 

또는 또 다른 옵션은 운영자가

public class Parent 
{ 
    public int age; 
    public static Parent operator +(Parent a, Parent b) 
    { 
     return new Parent(a, b); 
    } 

    protected Parent(Parent a, Parent b) 
    { 
     this.age = a.age + b.age; 
    } 
} 

public class Child : Parent 
{ 
    public static Child operator +(Child a, Child b) 
    { 
     return new Child(a, b); 
    } 

    protected Child(Child a, Child b) : base(a,b) 
    { 
     // anything you need to do for adding children on top of the parent code. 
    } 
}