[C++] 상속 : 부모 몬스터 <--- 자식 드래곤

2022. 6. 10. 16:49코딩 1막 <C++개념편>/코딩 1막 <C++응용편>

728x90

#include <iostream>
#include <string>

using namespace std;

struct Monster
{
    string name;
    int hp;
    int atk;
    int isChase;
    
    Monster(string _name, int _hp, int _atk, bool _isChase)
    {
        name = _name;
        hp = _hp;
        atk = _atk;
        isChase = _isChase;
    }

    void Attack()
    {
        cout << name << " 공격" << endl;
    }
    void Hit()
    {
        cout << name << " 맞음" << endl;
    }
    void Die()
    {
        cout << name << " 죽음" << endl;
    }
    void ChaseTarget()
    {
        cout << name << " 쫒아감" << endl;
    }
};

struct Dragon : Monster
{
    bool isFly;

    // 부모의 생성자를 사용해서 초기화를 편하게 할 수 있음
    Dragon(string _name, int _hp, int _atk, bool _isChase, bool _isFly) : Monster(_name, _hp, _atk, _isChase)
    {
        isFly = _isFly;
    }

    void Fly()
    {
        cout << name << " 날아감" << endl;
    }
};


void main()
{
    Dragon dragon("드래곤", 100, 10, true, true);
    dragon.Attack();
    dragon.Hit();
    dragon.Die();
    dragon.ChaseTarget();
    dragon.Fly();
}

출력 결과

* 고찰

- 부모의 생성자를 사용해서 자식의 생성자 초기화를 편하게 할 수 있다

728x90