virtual(가상함수) 연습해본거..
Barrack 에서 육군, 해군, 공군을 뽑아서 Attack(Virtual 함수) 을 실행하면 자기한테 맞는 공격을 취한다.
#ads_1
#include <iostream>
using namespace std;
class Soldier{
protected:
char *name;
char *weapon;
public:
virtual ~Soldier();
const char* GetName() const;
const char* GetWeapon() const;
virtual void Attack() const = 0;
};
Soldier::~Soldier(){
delete[] name; //null 체크할 필요 없다 알아서 한다
delete[] weapon;
cout << "~Soldier()" << endl;
}
const char* Soldier::GetName() const{
return name;
}
const char* Soldier::GetWeapon() const{
return weapon;
}
class Army: public Soldier{
public:
Army();
virtual ~Army();
virtual void Attack() const;
};
Army::Army(){
name = new char[strlen("육군") + 1];
strcpy(name, "육군");
weapon = new char[strlen("소총") + 1];
strcpy(weapon, "소총");
}
Army::~Army(){
cout << "~Army()" << endl;
}
void Army::Attack() const{
cout << "지상에서 공격합니다" << endl;
}
class Marine: public Soldier{
public:
Marine();
~Marine();
virtual void Attack() const;
};
Marine::Marine(){
name = new char[strlen("해군") + 1];
strcpy(name, "해군");
weapon = new char[strlen("구축함") + 1];
strcpy(weapon, "구축함");
}
Marine::~Marine(){
cout << "~Marine()" << endl;
}
void Marine::Attack() const{
cout << "바다에서 공격합니다" << endl;
}
class Airforce: public Soldier{
public:
Airforce();
~Airforce();
virtual void Attack() const;
};
Airforce::Airforce(){
name = new char[strlen("공군") + 1];
strcpy(name, "공군");
weapon = new char[strlen("비행기") + 1];
strcpy(weapon, "비행기");
}
Airforce::~Airforce(){
cout << "~Airforce()" << endl;
}
void Airforce::Attack() const{
cout << "공중에서 공격합니다" << endl;
}
class Barrack{
private:
Soldier **sol_list;
int cnt;
public:
static const enum SoldierType{stArmy, stMarine, stAirFoce};
Barrack():sol_list(NULL), cnt(0){;}
~Barrack();
Soldier *CreateSoldier(int type);
int GetCount() const;
};
Barrack::~Barrack(){
if(sol_list == NULL) return;
free(sol_list);
}
Soldier *Barrack::CreateSoldier(int type){
cnt++;
if(sol_list == NULL){
sol_list = (Soldier **)malloc(sizeof(Soldier*) * (cnt));
}else{
sol_list = (Soldier **)realloc(sol_list, sizeof(Soldier*) * (cnt));
}
switch(type){
case stMarine:
sol_list[cnt-1] = new Marine();
break;
case stAirFoce:
sol_list[cnt-1] = new Airforce();
break;
default:
sol_list[cnt-1] = new Army();
}
return sol_list[cnt-1];
}
int Barrack::GetCount() const{
return cnt;
}
void main(){
Barrack br;
Soldier *s1 = br.CreateSoldier(Barrack::stArmy);
cout << "이름 : " << s1->GetName() << endl;
cout << "무기 : " << s1->GetWeapon() << endl;
s1->Attack();
cout << "--------------------------------\n";
Soldier *s2 = br.CreateSoldier(Barrack::stAirFoce);
cout << "이름 : " << s2->GetName() << endl;
cout << "무기 : " << s2->GetWeapon() << endl;
s2->Attack();
cout << "--------------------------------\n";
Soldier *s3 = br.CreateSoldier(Barrack::stMarine);
cout << "이름 : " << s3->GetName() << endl;
cout << "무기 : " << s3->GetWeapon() << endl;
s3->Attack();
cout << "총 군인수 : " << br.GetCount() << endl;
delete s1;
delete s2;
delete s3;
}
#ads_1