2016. 4. 14. 11:09

오버라이딩(Overriding)


※ 오버라이딩은 함수의 재정의를 말합니다.

※ 상속받은 자식 클래스에서 부모 클래스의 멤버 함수를 재정의 하는것을 말합니다.


오버로딩(Overloading)


※ 오버로딩은 함수의 중복 선언을 말합니다.

※ 같은 함수에서 인수만 다르면 얼마든지 정의할 수 있습니다.



===============================================

오버라이딩의 예


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
 
class _Parent{
public:
    void Something()
    {
        cout << "_Parent Shomthing Function" << endl;
    }
};
 
//자식클래스01
class _Children:public pitching
{
};
 
//자식클래스02
class _OtherChildren:public pitching
{
public:
    //함수 재정의(오버라이딩)
    void Something()
    {
        cout << "_OtherChildren Shomthing Function" << endl;
    }
};
 
void main()
{
    //_Children 객체생성 후 함수호출
    _Children *Children = NULL;
    Children->Something();
 
    //_OtherChildren 객체 생성 후 함수호출
    _OtherChildren *OtherChildren=NULL;
    OtherChildren->Something();
}
 
cs


위 함수의 결과가 어떻게 나올까요?


결과는

-----------------------------------------------

_Parent Shomthing Function

_OtherChildren Shomthing Function

-----------------------------------------------


이렇게 나온답니다.

이유는 Children객체는 상속받은 부모의 함수를 실행하지만, OtherChildren은 클래스내에서 재 정의한 함수를 호출하기 때문입니다.


이처럼 부모와 똑같은 함수명, 파라미터를 가지고 자식클래스에서 새롭게 정의하여 사용하는것을 오버라이딩이라고합니다.


===============================================


오버 로딩의 예


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
class Overload{
    public void Something()
    {
        cout << "Shomthing() Function" << endl;
    }
    public void Something(int _cnt,int _cnt)
    {
        cout << "Shomthing(int _cnt,int _cnt) Function" << endl;
    }
    public void Something(double _num)
    {
        cout << "Shomthing(double _num) Function" << endl;
    }
}
 
void main() {
        Overload ob = new Over();
        ob.Something(1,2);
        ob.Something(3);
}
cs


출력결과는

-----------------------------------------------

Shomthing() Function

Shomthing(int _cnt,int _cnt) Function

Shomthing(double _num) Function

-----------------------------------------------


입니다.

이유는 함수의 인자가 다르기 때문입니다. 각각의 맞는 인자로 알아서 호출된답니다.

이처럼 같은 함수내에서 인자로 구분되어 정의하는것을 오버로딩 이라고 합니다.



Posted by 시리시안