1.思维导图
2.
3.
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>
using namespace std;
class Hero{
private:
int atk;
int def;
int spd;
int hp;
public:
Hero(int a,int d,int s,int h):atk(atk),def(def),spd(spd),hp(hp)
{
atk=a;
def=d;
spd=s;
hp=h;
}
void set_atk(int val){atk+=val;}
void set_def(int val){def+=val;}
void set_spd(int val){spd+=val;}
void set_hp(int val){hp+=val;}
int get_atk(){return atk;}
int get_def(){return def;}
int get_spd(){return spd;}
int get_hp(){return hp;}
void equipWeapon(class Weapon * w);
void show()
{
cout<<"atk= "<<atk<<endl;
cout<<"def= "<<def<<endl;
cout<<"spd= "<<spd<<endl;
cout<<"hp= "<<hp<<endl;
}
};
class Weapon{
private:
int atk;
public:
Weapon():atk(50){}
void set_atk(int val){atk=val;}
int get_atk(){return atk;}
virtual int* equip()=0;
};
class Sword:public Weapon{
private:
int hp;
public:
Sword():hp(50){}
void set_hp(int val){hp=val;}
int get_hp(){return hp;}
int* equip()
{
int att=get_atk();
int d=0;
int s=0;
int h=hp;
int* arr=new int[4]{att,d,s,h};
return arr;
}
};
class Blade:public Weapon{
private:
int spd;
public:
Blade():spd(50){}
void set_spd(int val){spd=val;}
int get_spd(){return spd;}
int* equip()
{
int att=get_atk();
int d=0;
int s=spd;
int h=0;
int* arr=new int[4]{att,d,s,h};
return arr;
}
};
class Axe:public Weapon{
private:
int def;
public:
void set_def(int val){def=val;}
int get_def(){return def;}
int* equip()
{
int att=get_atk();
int d=def;
int s=0;
int h=0;
int* arr=new int[4]{att,d,s,h};
return arr;
}
};
void Hero::equipWeapon(class Weapon* w)
{
int* data=w->equip();
set_atk(data[0]);
set_def(data[1]);
set_spd(data[2]);
set_hp(data[3]);
delete[] data;
}
int main(int argc,const char** argv){
Hero lwl(100,50,50,200);
Sword sword;
Blade blade;
Axe axe;
Weapon* w[4]={&sword,&blade,&axe};
lwl.equipWeapon(w[0]);
lwl.show();
}