회원 로그인
정보기억 정보기억에 체크할 경우 다음접속시 아이디와 패스워드를 입력하지 않으셔도 됩니다.
그러나, 개인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 | 조회 4752
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개(1/15페이지)
프로그래밍
번호 제목 글쓴이 조회 날짜
285 [Python] 동적 import - 모듈을 변수로 받아오기 푸딩뱃살 412 2022.10.27 10:45
284 [Python] 파이썬 3.7.7과 3.9.7의 os.path.expanduser() 차이 푸딩뱃살 455 2022.08.18 12:22
283 [Python] error: Microsoft Visual C++ 9.0 is required. 첨부파일 푸딩뱃살 684 2022.08.03 13:35
282 [Python] pyscript 첨부파일 푸딩뱃살 453 2022.06.09 11:21
281 [Python] float is / float not is 푸딩뱃살 593 2022.03.02 15:03
280 [Python] 이터널 문자열 f 푸딩뱃살 833 2022.01.27 16:35
279 [Python] is와 ==의 차이 푸딩뱃살 485 2021.11.25 15:54
278 [Python] Error: ImportError: file line 1: Ba 푸딩뱃살 916 2021.11.16 11:24
277 [Python] 파이썬 디컴파일 - uncompyle6 첨부파일 푸딩뱃살 774 2021.11.10 14:46
276 [Python] 파이썬 확장자 설명 푸딩뱃살 550 2021.11.03 14:38
275 [참고] 웹 fbx 뷰어 푸딩뱃살 470 2021.10.19 15:46
274 [Python] enumerate() 푸딩뱃살 500 2021.10.13 14:44
273 [Python] 아나콘다에서 가상 환경 첨부파일 푸딩뱃살 719 2020.11.21 00:26
272 [Python] pip로 설치 때 퍼미션 에러 사진 첨부파일 푸딩뱃살 1265 2020.06.06 17:13
271 [Python] OpenCV 10-3. 이미지 Thresholding - Otsu's Binarizatio 사진 푸딩뱃살 673 2020.06.05 14:01
270 [Python] OpenCV 10-2. 이미지 Thresholding - Adaptive Threshold 사진 푸딩뱃살 694 2020.06.05 13:58
269 [Python] OpenCV 10-1. 이미지 Thresholding 사진 푸딩뱃살 578 2020.06.05 13:56
268 [Python] OpenCV 9-2. 색 추적 푸딩뱃살 772 2020.06.02 23:29
267 [Python] OpenCV 9-1. 색공간 바꾸기 푸딩뱃살 639 2020.06.02 23:27
266 [Python] OpenCV 8-3. 이미지 비트 연산 사진 푸딩뱃살 528 2020.06.02 23:21