[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
'코딩 1막 <C++개념편> > 코딩 1막 <C++응용편>' 카테고리의 다른 글
[C++] 가상함수를 써서 플레이어를 생성하는 함수를 호출해보자 (0) | 2022.06.13 |
---|---|
[C++] 구조체 만들고, 상속해보고, 오버로딩, 오버라이딩 및 가상함수 구현해보기 (0) | 2022.06.10 |
[C++] 동적할당을 써서 별찍기, 배수의 배열 그리고 배열범위 넓히기★ (0) | 2022.06.07 |
[C++] 구조체 변수의 동적할당과 해제 (0) | 2022.06.07 |
[C++] 참조자를 사용해서 swap함수 만들기 (0) | 2022.06.07 |