多文件组织多个类程序

用多个cpp文件实现上一个带武器的角色,将头文件保存在.h的文件中。


(1)weapon.h

#ifndef WEAPON_H_INCLUDED
#define WEAPON_H_INCLUDED
#include<string>
using namespace std;
class weapon
{
public:
	weapon(string na,int po)
	{
		name=na;
		power=po;
	}
	int getpower();
	string getname();
private:
	string name;
	int power;
};
#endif // WEAPON_H_INCLUDED
(2)Role.h

#include"weapon.h"
#include<string>
using namespace std;
class Role
{
public:
	Role(string nam,int n,string we,int p);
	~Role();
	void show();
	void attack(Role &other);
	void eat(int n);
	void beAttack(Role &other);
	bool isAlive();
	string getname();
private:
	string name;
	int blood;
	weapon weapon;
	bool life;
};
(3)game.cpp

#include"weapon.h"
#include"Role.h"
#include<iostream>
using namespace std;

string weapon::getname()
{
	return name;
}
int weapon::getpower()
{
	return power;
}
string Role::getname()
{
	return name;
}
void Role::attack(Role &other)
{
	if(isAlive())
	{
		cout<<name<<"使用"<<weapon.getname()<<"攻击"<<other.getname()<<',';
		cout<<other.getname()<<"损失"<<weapon.getpower()<<"滴血,";
		cout<<name<<"得到"<<weapon.getpower()<<"滴血"<<endl;
		blood+=weapon.getpower();
		other.blood-=weapon.getpower();
		if(other.blood<=0)
			life=false;
	}
}
void Role::eat(int n)
{
	if(isAlive())
		cout<<name<<"吃了一个苹果,血量增加"<<n<<"点"<<endl;
		blood+=n;
}
void Role::beAttack(Role &other)
{
	if(isAlive())
	{
		cout<<other.getname()<<"使用"<<other.weapon.getname()<<"攻击"<<name<<',';
		cout<<name<<"损失"<<other.weapon.getpower()<<"滴血,";
		cout<<other.getname()<<"得到"<<other.weapon.getpower()<<"滴血"<<endl;
		blood-=other.weapon.getpower();
		other.blood+=weapon.getpower();
		if(blood<=0)
			life=false;
	}		
}
bool Role::isAlive()
{
	return life;
}
Role::Role(string nam,int n,string we,int p):name(nam),blood(n),weapon(we,p)
{
//	this->name=nam;
//	this->blood=n;
//	this->weapon.name=we;
//	this->weapon.power=p;
	if(blood>0)
		life= true;
	else
		life= false;
}
Role::~Role()
{
	if(blood<=0)
	cout<<name<<"退出江湖"<<endl;
}

void Role::show()
{
	if(blood>0)
	cout<<name<<"还剩"<<blood<<"滴血"<<endl;
}
(4)main.cpp

#include<iostream>
#include<string>
#include"Role.h"
#include"weapon.h"
using namespace std;
int main( )
{
	int i=1;
	cout<<"初始状态:"<<endl;
	Role mary("Mary", 100,"灵兽刀",90);
	Role jack("Jack", 100,"张扬剑",10);
	mary.show();
	jack.show();
	cout<<"第一回合:"<<endl;
	mary.attack(jack);
	mary.beAttack(jack);
	jack.attack(mary);
	jack.beAttack(mary);
	jack.eat(5);
	mary.show();
	jack.show();
	cout<<"第二回合:"<<endl;
	mary.attack(jack);
	mary.beAttack(jack);
	jack.attack(mary);
	jack.beAttack(mary);
	mary.show();
	jack.show();
	return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值