1.game.h:类声明
#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
using namespace std;
class Role
{
public:
void setRole(string M,int x);
void weapon1(int );
void weapon2(int );
bool show();
void attack();
void eat(int );
void beAttack();
private:
string name;
int blood;
bool life;
int shanghai=1;
};
class Weapon
{
public:
void weapon1(int n);
void weapon2(int n);
private:
int shanghai=1;
};
#endif
2.role.cpp:定义角色类的成员函数
#include <iostream>
#include "game.h"
using namespace std;
void Role::setRole(string M,int x)
{
blood=x;
cout<<"名字:"<<M<<"生命力:"<<blood<<endl;
}
bool Role::show()
{
if(blood>0)
cout<<"生命力:"<<blood<<endl;
else
cout<<"无生命力"<<endl;
return 0;
}
void Role::attack()
{
cout<<"您造成了"<<shanghai<<"点伤害"<<endl;
}
void Role::eat(int n)
{
blood+=n;
cout<<"您得到"<<n<<"点生命"<<endl;
}
void Role::beAttack()
{
blood=blood-1;
cout<<"您减少"<<1<<"点生命"<<endl;
}
3.weapon.cpp:武器类的成员函数的实现
#include <iostream>
#include "game.h"
using namespace std;
void Role::weapon1(int n)
{
cout<<"断念剑伤害为"<<n<<endl;
shanghai+=n;
}
void Role::weapon2(int n)
{
cout<<"勃朗宁伤害为"<<n<<endl;
shanghai+=n;
}
4.main.cpp:测试函数
#include <iostream>
#include "game.h"
using namespace std;
int main()
{
int x;
Role mary;
mary.setRole("Mary",4);
mary.show();
cout<<"请选择武器:1、断念剑。2、勃朗宁"<<endl;
cin>>x;
switch(x)
{
case 1:
mary.weapon1(2);break;
case 2:
mary.weapon2(20);break;
}
mary.attack();
mary.eat(2);
mary.beAttack();
mary.beAttack();
mary.show();
return 0;
}
运行结果: