회원 로그인
정보기억 정보기억에 체크할 경우 다음접속시 아이디와 패스워드를 입력하지 않으셔도 됩니다.
그러나, 개인PC가 아닐 경우 타인이 로그인할 수 있습니다.
PC를 여러사람이 사용하는 공공장소에서는 체크하지 마세요.
소셜네트워크 서비스를 통해서 로그인하시면 별도의 로그인 절차없이 회원서비스를 이용하실 수 있습니다.


최근 게시물

1.노션에서 작성 중

1.노션에서 작성 중

개편하기 전까지 노션에서 작성 중

2024.04.04//read more

2.ChatGPT

2.ChatGPT

OpenAI로 대규모 언어 모델대화형...

2023.03.16//read more

3.노코딩 게임 엔진 - 빌..

3.노코딩 게임 엔진 - 빌..

빌드 지원안드로이드iOS윈도우즈특이사...

2023.03.14//read more

4.(완료) 미접속 회원 정..

4.(완료) 미접속 회원 정..

[완료] 36명의 회원을 정리하였습니...

2023.02.16//read more

5.매뉴얼 플러스 - 전자제..



안정적인 DNS 서비스 DNSEver
DNS Powered by DNSEver.com


추상 클래스 - 오버라이드 / 업/다운캐스팅(형변환) / virtual(가상함수)

푸딩뱃살 | 2015.11.12 02:00 | 조회 4726
C++ 추상 클래스

[메소드 오버라이드]
- 기반 클래스(부모)에서 상속 받은 메소드를 파생 클래스(자식)에서 재정의 해서 사용하는 것을 메소드 오버라이드라고 한다.

[업캐스팅]
- 파생 클래스(자식) 타입의 객체를 기반 클래스(부모) 타입으로 형 변환하는 것을 업캐스팅이라고 함
- 업캐스팅은 자동적으로 형 변환 됨
- 업캐스팅 문법 : 기반클래스* 인스턴스 = new 파생클래스()

[다운캐스팅]
- 기반 클래스(부모)로 이미 형 변환 된 파생 객체를 다시 파생 클래스(자식) 타입으로 형 변환 하는 것을 다운캐스팅이라고 함
- 다운 캐스팅은 반드시 강제적으로 수행해야 함
- 다운캐스팅 문법 : 파생클래스* 인스턴스 = (파생클래스 *)기반클래스로 업캐스팅된 객체인스턴스

[가상 함수] virtual
- 업캐스팅 된 상태에서 메소드를 호출할 경우 오버라이드된 파생 클래스의 메소드가 아닌 기반클래스의 메소드가 호출된다.
이때 기반 클래스의 메소드를 가상 함수로 만들면 오버라이드 된 파생 클래스의 메소드가 호출된다.

[문법]
class 기반클래스 {
public:
    virtual 오브라이드메소드() { .. }
}

class 파생클래스 : 기반클래스 {
public:
    오버라이드메소드() { .. }

/*
추상 클래스
*/
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

// 완전 가상함수를 가진 추상 클래스(인터페이스)
class CommonUnit4 {
protected:
    string _name;
    int _hp;
    int _damage;
public:
    CommonUnit4() {    }

    CommonUnit4(string name, int damage) {
        _name = name;
        _damage = damage;
    }
    virtual ~CommonUnit4() {} // 파생 클래스 소멸자가 호출되도록

    virtual void Move() = 0;

    void Attack() {
        cout << "[" << _name.c_str() << "] 님이 " << _damage << "만큼의 공격" << endl;
    }

    void Hit(int damage) {
        cout << "[" << _name.c_str() << "] 님이 " << _damage << "데미지" << endl;
    }

    void Die() {
        cout << "[" << _name.c_str() << "] 님이 사망" << endl;
    }
};

class Player4 : public CommonUnit4 {
private:
    int _level;
    int _gravity;
    string _talkMessage;
public:
    Player4(string name, int damage, string talkMessage) : CommonUnit4(name, damage) {
        _talkMessage = talkMessage;

        cout << "[" << _name.c_str() << "] 님이 접속" << endl;

    }
    ~Player4() {}

    void Talk() {
        cout << "[" << _name.c_str() << "] 님이 커서 방향으로 이동" << endl;
    }

    void Attack() {
        cout << "[" << _name.c_str() << "] 님이 총을 쏘면서 피하면서 " << _damage << "만큼의 공격" << endl;
    }

    void Jump() {
        cout << "[" << _name.c_str() << "] 님이 점프" << endl;
    }
};

class Monster4 : public CommonUnit4 {
private:
    int _skillType;
public:
    Monster4(string name, int damage, int skillType) : CommonUnit4(name, damage) {
        _skillType = skillType;
        cout << "[" << _name.c_str() << "] 님이 나타났다" << endl;
    }
    ~Monster4() {}

    // 이동 메소드를 오버라이드 함
    void Move() {
        cout << "[" << _name.c_str() << "] 님이 플레이어를 향해 이동" << endl;
    }

    void Skill() {
        cout << "[" << _name.c_str() << "] 님이 " << _skillType << " 타입의 스킬 사용" << endl;
    }
};

class Creature4 : public CommonUnit4 {
private:
    int _time;
public:
    Creature4(string name, int damage, int time) : CommonUnit4(name, damage) {
        _time = time;
        cout << "[" << _name.c_str() << "] 님이 소환" << endl;
    }
    ~Creature4() {}

    // 이동 메소드를 오버라이드 함
    void Move() {
        cout << "[" << _name.c_str() << "] 님이 공중으로 이동" << endl;
    }

    // 오버라이드
    void Hit(int damage) {
        // 부모의 Hit 메소드를 호출
        CommonUnit4::Hit(damage);
        Attack();  // 크리쳐는 공격을 받으면 공격을 시도함
    }

    void Timer() {
        cout << "[" << _name.c_str() << "] 님이 " << _time << " 시간뒤에 소멸" << endl;
    }
};

class Stage4 {
private:
    int stageNum;
public:
    // 업캐스팅 활용 전
    // 타입이 늘어날 경우 같은 메소드가 계속 추가되어야 함
    void PlayerMove(Player4* player) {
        player->Move();
    }
    void MonsterMove(Monster4* monster) {
        monster->Move();
    }
    void CreatureMove(Creature4* creature) {
        creature->Move();
    }
    // 업캐스팅을 활용한 후
    void UnitsMove(CommonUnit4** units, int size) {
        for (int i = 0; i < size; i++) {
            units[i]->Move(); // 크리쳐는 공중으로 이동하나요?
        }
    }
    void MoverMove(CommonUnit4** units, int size) {
        for (int i = 0; i < size; i++) {
            units[i]->Move();  // 크리쳐는 공중으로 이동하나요?
        }
    }
};

class ExtendsStudy4 {
public:
    ExtendsStudy4() {
        Start();
    }

    void Start() {
        // 부모 타입 포인터 변수
        CommonUnit4* unit;

        Player4* player = new Player4("푸딩", 30, "뱃살 친구");

        // 업캐스팅
        unit = player;

        unit->Move();
        unit->Attack();
        unit->Hit(10);
        unit->Die();
        
        // unit->Jump();

        // 다운 캐스팅
        Player4* tmpPlayer = (Player4 *)unit;
        tmpPlayer->Jump;

        Stage4* stage = new Stage4();
        // 몬스터 타입에 플레이어 인스턴스를 넘겨줄 수 없음
        // stage->MonsterMove(player);
        stage->PlayerMove(player);

        Monster4* monster = new Monster4("고블린", 10, 1);
        Creature4* creature = new Creature4("멀록", 5, 10);

        // 업캐스팅을 활용한 다형성 및 가상함수 테스트
        CommonUnit4* units[3];
        units[0] = player;
        units[1] = monster;
        units[2] = creature;

        // 업캐스팅을 이용한 다형성
        stage->UnitsMove(units, 3);

        // 순수 가상함수 테스트
        CommonUnit4* movers[3];
        movers[0] = player;
        movers[1] = monster;
        movers[2] = creature;

        stage->MoverMove(movers, 3);
        for (int i = 0; i < 3; i++) {
            delete units[i];
        }
    }
};

void main4() {
    ExtendsStudy4* object = new ExtendsStudy4();
    delete object;
}

정리..중...
// 추상 클래스
class 클래스A {
protected:
    ......
public:
    // 오버로드
    void 클래스A() {
    }

    // 메소드
    void 메소드A() {
    }

    // 메소드들
    void 메소드들() {
    }

    // 순수 가상 함수
    // 진짜 가상 함수
    virtual void 메소드B() = 0;
}

// 오버라이드
class 클래스B : 클래스A {
private:
    ......
public:
    // 오버로드
    void 클래스B() {
    }

    // 오버라이드 
    void 클래스A의 메소드A() {
    }
}

// 업캐스팅 / 다운캐스팅
class 클래스C {
public:
    void 메소드() {
    // 부모의 타입 포인터 변수 생성
    클래스A* 변수A;
    클래스B* 변수B = new 클래스B(오버로드);

    // 업캐스팅
    변수A = 변수B;
    변수A->클래스A의 메소드들();

    // 다운캐스팅
    }

}
285개(7/15페이지)
프로그래밍
번호 제목 글쓴이 조회 날짜
165 [C#] 네임스페이스 (namespace) 푸딩뱃살 3406 2015.11.14 17:34
164 [C#] 인터페이스 (Interface) 첨부파일 푸딩뱃살 2196 2015.11.13 18:17
163 [C/C++] Static(정적) 멤버 변수, 메소드 푸딩뱃살 2474 2015.11.13 10:32
>> [C/C++] 추상 클래스 - 오버라이드 / 업/다운캐스팅(형변환) / virtual(가상함수) 푸딩뱃살 4727 2015.11.12 02:00
161 [C/C++] 메소드 오버라이드 푸딩뱃살 1993 2015.11.12 01:51
160 [C#] 상속 (with Unity) 푸딩뱃살 5455 2015.11.10 16:25
159 [C/C++] 클래스 상속 푸딩뱃살 2246 2015.11.10 14:08
158 [C/C++] 객체 활용 푸딩뱃살 2472 2015.11.09 21:28
157 [C#] C# 객체 클래스 푸딩뱃살 3569 2015.11.08 15:51
156 [C/C++] 생성자 / 소멸자 / 오버로드 푸딩뱃살 2203 2015.11.07 01:23
155 [C/C++] 클래스 선언/정의, 객체 생성 푸딩뱃살 3568 2015.11.06 14:05
154 [C/C++] 로또 프로그램 푸딩뱃살 2286 2015.11.06 12:00
153 [C/C++] 2차원 동적 객체 배열 활용 푸딩뱃살 3650 2015.11.06 00:47
152 [C/C++] 2차원 배열 푸딩뱃살 2404 2015.11.06 00:30
151 [C/C++] 2차원 포인터 푸딩뱃살 2053 2015.11.06 00:26
150 [C/C++] 동적할당 푸딩뱃살 1806 2015.11.05 11:23
149 [C/C++] 당신의 프로그래밍에 디버깅 더하기 : Visual C++ 디버깅 기초에서 고급까지 첨부파일 푸딩뱃살 1454 2015.11.05 11:20
148 [C/C++] 포인터와 배열의 이해 푸딩뱃살 2014 2015.11.04 23:54
147 [C/C++] 포인터 푸딩뱃살 2195 2015.11.04 15:14
146 [C/C++] 일반 함수와 메소드간의 차이 푸딩뱃살 2433 2015.11.03 23:38