5.28 c++作业

1.牛客刷题

5.28 c++作业_第1张图片

5.28 c++作业_第2张图片 

2.写一个英雄类

class Hero{
    int atk;
    int def;
    int spd;
    int hp;
public:
    构造函数
    4个属性的set,get接口
    void equipWeapon(参数传入具体的武器){
        如果传入短剑:英雄增加1点攻击力 和 1点速度
        如果传入长剑:英雄增加1点攻击力 和 1点生命值
        如果传入斧头:英雄增加1点攻击力 和 1点防御力
    }
    void show();输出英雄当前的属性值
}

再写3个武器类
class Blade{
    短剑        
}
class Sword{
    长剑    
}
class Axe{
    斧头
}

#include 

using namespace std;

class Hero;

//武器基类
class Weapon{
	public:
		//加成
		virtual void bonus(Hero& hero)
		{}
};
class Hero{
	int atk;
	int def;
	int spd;
	int hp;
public:
	//构造函数
	Hero(const int& atk = 0, const int& def = 0, const int& spd = 0, const int& hp = 0)
		: atk(atk), def(def), spd(spd), hp(hp)
	{}
	//4个属性的set,get接口
	void set_atk(const int&_atk)
	{
		this->atk = _atk;
	}
	void set_def(const int&_def)
	{
		this->def = _def;
	}
	void set_spd(const int&_spd)
	{
		this->spd = _spd;
	}
	void set_hp(const int&_hp)
	{
		this->hp = _hp;
	}
	int get_atk()
	{
		return this->atk;
	}
	int get_def()
	{
		return this->def;
	}
	int get_spd()
	{
		return this->spd;
	}
	int get_hp()
	{
		return this->hp;
	}
	/*如果传入短剑:英雄增加1点攻击力 和 1点速度
	  如果传入长剑:英雄增加1点攻击力 和 1点生命值
	  如果传入斧头:英雄增加1点攻击力 和 1点防御力*/
	void equipWeapon(Weapon* weapon){
		weapon->bonus(*this); 
	}
	// 输出英雄当前的属性值
	void show(){
		cout << "atk = " << atk << endl;
		cout << "def = " << def << endl;
		cout << "spd = " << spd << endl;
		cout << "hp = " << hp << endl;
	}
};



//再写3个武器类
class Blade:public Weapon{
	//短剑
	void bonus(Hero& hero)
	{
		int _atk = hero.get_atk();
		int _spd = hero.get_spd();
		_atk++;
		_spd++;
		hero.set_atk(_atk);
		hero.set_spd(_spd);
	}
};

class Sword:public Weapon{
	//长剑
	void bonus(Hero& hero)
	{
		int _atk = hero.get_atk();
		int _hp = hero.get_hp();
		_atk++;
		_hp++;
		hero.set_atk(_atk);
		hero.set_hp(_hp);
	}
};

class Axe:public Weapon{
	//斧头
	void bonus(Hero& hero)
	{
		int _atk = hero.get_atk();
		int _def = hero.get_def();
		_atk++;
		_def++;
		hero.set_atk(_atk);
		hero.set_def(_def);
	}
};


int main()
{
	//超绝普通小兵
	Hero hero = Hero(5,5,5,100);
	hero.show();
	hero.equipWeapon(new Blade);
	hero.show();
	hero.equipWeapon(new Sword);
	hero.show();
	hero.equipWeapon(new Axe);
	hero.show();
	return 0;
}

 

 

你可能感兴趣的:(c++,算法,多态,linux,继承)