[C++] 가상함수를 써서 플레이어를 생성하는 함수를 호출해보자

2022. 6. 13. 20:54코딩 1막 <C++개념편>/코딩 1막 <C++응용편>

728x90
#include <iostream>
#include <string>

using namespace std;

struct Class
{
	void virtual Attack()
	{
		cout << "공격" << endl;
	}
	virtual ~Class()
	{
		cout << "클래스 소멸자" << endl;
	}
};

struct Warrior : Class
{
	void Attack()
	{
		cout << "근접 공격" << endl;
	}
	~Warrior()
	{
		cout << "워리어 소멸자" << endl;
	}
};

struct Archer : Class
{
	void Attack()
	{
		cout << "원거리 공격" << endl;
	}
	~Archer()
	{
		cout << "아처 소멸자" << endl;
	}

};

struct Player
{
	string name;
	Class* playerClass;	// has a 관계

	void Attack()
	{
		cout << name << "이 공격한다" << endl;
		playerClass->Attack();
	}
	~Player()
	{
		cout << "플레이어 소멸자" << endl;
		delete playerClass;
	}
};

// {}가 끝나도 정보가 유지되고싶어서 동적할당을 시킨것
Player* CreatePlayer()
{
	int input;
	Player* tempPlayer = new Player;

	cout << "플레이어를 생산합니다" << endl;
	cout << "플레이어 이름 입력 : " ;
	cin >> tempPlayer->name;
	
	cout << "플레이어 직업을 선택하시오 (1. 전사 2. 궁수) : " << endl;
	cin >> input;

	if (input == 1)
	{
		tempPlayer->playerClass = new Warrior();
	}
	else
	{
		tempPlayer->playerClass = new Archer();
	}
	return tempPlayer;
}

void main()
{
	Player* player = CreatePlayer();
	player->Attack();

	delete player;
}

출력 결과

 

728x90