您的位置:首页 > 其它

补充程序之游戏系列— 3 多文件组织多个类的程序

2016-06-08 15:55 344 查看

*Copyright(c) 2016.烟台大学计算机与控制工程学院

*ALL rights  reserved.

*文件名称:main.cpp

*作者:孙亚茹

*完成日期:2016年6月8日

*问题描述:将”项目2—带武器的游戏角色“用”一个项目多个文件“的方式实现,其中两个类的声明放在一个.h文件中,每个类的成员函数分别放入一个文件中,main()函数用一个文件。

*//

game.h  类的声明:

<pre class="cpp" name="code">#ifndef GAME_H
#define GAME_H
using namespace std;
class Wuqi
{
private:
string name;
string type;
int force;
public:
Wuqi(string nam,string ty,int f):name(nam),type(ty),force(f){};
void show();
int getForce();
};
class Role
{
public:
Role(string nam,int b,string nam1,string ty1,int f1):name(nam),blood(b),w(nam1,ty1,f1) {};
~Role();
void show();
void attack(Role &r);
void eat(int n);
bool isLife();
private:
string name;
int blood;
bool life;
Wuqi w;
};
#endif // GAME_H


Role.cpp   角色类成员函数:

#include<iostream>
#include<game.h>
using namespace std;
void Wuqi::show()
{
cout<<"所用武器名字为:"<<name<<" "<<"所属系别是:"<<type<<" "<<"杀伤力是:"<<force<<endl;
}
int Wuqi::getForce()
{
return force;
}

Wuqi.cpp 武器类成员函数:

#include<iostream>
#include<game.h>、
using namespace std;
bool Role::isLife()
{
if(blood>0)
return true;
else
return false;
}
Role::~Role()
{
cout<<name<<"退出江湖..."<<endl;
}
void Role::attack(Role &r)
{
if(isLife())
{
blood+=w.getForce();
r.blood-=w.getForce();
}
}
void Role::eat(int n)
{
if(isLife())
{
blood+=n;
}
}
void Role::show()
{
if(isLife())
{

cout<<name<<"还有"<<blood<<"滴血"<<"  ";
w.show();
}
else
cout<<name<<"已经死了"<<endl;
}

main.cpp  主函数:

#include<iostream>
#include<game.h>
using namespace std;
int main()
{
Wuqi w1("倚天剑","剑系",4);
Wuqi w2("屠龙刀","刀系",3);
Role mary("Mary",4,"倚天剑","剑系",2);
Role jack("Jack",3,"屠龙刀","刀系",1);
mary.show();
jack.show();
int n;
while(1)
{
cout<<" 1 maryAttack 2 maryEat 3 jackAttack 4 jackEat"<<endl;
cout<<"请您选择相应的动作:"<<endl;
cin>>n;
if(n==1)
{
mary.attack(jack);
mary.show();
jack.show();
cout<<endl;
}

else if(n==2)
{
mary.eat(2);
mary.show();
cout<<endl;
}
else if(n==3)
{
jack.attack(mary);
jack.show();
mary.show();
cout<<endl;
}

else if(n==4)
{
jack.eat(2);
jack.show();
cout<<endl;
}
else
break;
}
return 0;
}


总结:

        一个项目,由多个源文件及相应的头文件构成,将声明与定义分开。

        文件还是不太明白,还要去多理解,学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: