C++ 多态作业练习

发布于:2024-11-27 ⋅ 阅读:(82) ⋅ 点赞:(0)

作业1、

编写一个英雄类
class Hero{
    int atk;
    int def;
    int spd;
    int hp;
public:
    所有的get set 方法
    void equipWeapon(Weapon*)
    根据传入的武器不同,英雄获得不同的属性加成
}

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
using namespace std;

class Hero
{
private:
	int property; //属性
public:	
	Hero(int property = 0):property(property){}
	void addproperty(int buff)
	{
		property += buff;
	}

	int getproperty()
	{
		return property;
	}

	virtual void Igetproperty(){}
};

class atk: public Hero
{
public:
	atk(int property = 0):Hero(property){}
	virtual void Igetproperty()
	{
		addproperty(30);
	}
};

class def: public Hero
{
public:
	def(int property = 0):Hero(property){}
	virtual void Igetproperty()
	{
		addproperty(10);
	}

};

class spd: public Hero
{
public:
	spd(int property = 0):Hero(property){}
	virtual void Igetproperty()
	{ 
		addproperty(20);
	}

};

class hp: public Hero
{
public:	
	hp(int property = 0):Hero(property){}
	virtual void Igetproperty()
	{
   		addproperty(900);
	}

};

void propertyshow(Hero** addr)
{
	for(int i=0;addr[i]!= NULL;i++)
	{
		addr[i]->Igetproperty();
		cout << addr[i]->getproperty() << endl;
	}
}


int main(int argc,const char** argv)
{
	atk a;
	def b;
	spd c;
	hp d;
	Hero* addr[5] = {&a,&b,&c,&d};
	propertyshow(addr);

	return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到