第七周项目三-用多文件组织多个类的角色

来源:互联网 发布:jst java 编辑:程序博客网 时间:2024/06/02 20:53

问题及代码:

两个类的声明

#ifndef SHENGMING_H_INCLUDED#define SHENGMING_H_INCLUDED#include <iostream>using namespace std;class Weapon{public:    Weapon(string wnam, int w);    int getweili();private:    string wname;    int weili;};class Role{public:    Role(string nam,string clo,string wnam,int b=10,int e=0,int g=1,int w=0);  //构造函数    void changecloth(string clot);    void up_grade();    void attack(Role &r);    void eat(int a);    void show();    bool isAlived();    ~Role()      //析构函数    {        cout<<name<<"退出江湖..."<<endl;    }private:    string name;    string cloth;    Weapon weapon;    int w_arms;    int grade;    int emengy;    int blood;    bool life;};#endif // SHENGMING_H_INCLUDED

两个类的成员函数

#include"shengming.h"#include <cmath>Weapon::Weapon(string wnam, int w):wname(wnam),weili(w) {}int Weapon::getweili(){    return weili;}Role::Role(string nam,string clo,string wnam,int b,int e,int g,int w):name(nam),cloth(clo),blood(b),grade(g),emengy(e),weapon(wnam,w){    if(blood>0)        life=true;    else        life=false;}void Role::changecloth(string clot){    cloth=clot;}void Role::up_grade(){    if(isAlived()&&emengy>grade*10)        grade++;}void Role::attack(Role &r)   //攻击一次,血量+50,经验值加威力的十分之一{    if(isAlived())    {        blood+=50;        r.blood-=weapon.getweili();        if(r.blood<=0)            r.life=false;        emengy+=weapon.getweili()/10;    }}void Role::eat(int a)     //血量+a{    if(isAlived())        blood+=a;}bool Role::isAlived(){    return life;}void Role::show(){    up_grade();    cout<<name<<" has "<<blood<<" blood, it is ";    if(isAlived())        cout<<"alived."<<endl;    else        cout<<"dead."<<endl;;    cout<<"His grade is "<<grade<<",her emengy is "<<emengy<<"."<<endl;    cout<<"He is in "<<cloth<<" cloth."<<endl;    cout<<endl;}

main()函数

/**烟台大学计算机学院*文件名称:xiangmu1.cpp*作    者:闫安*完成日期:2016年4月30日*版 本 号:codeblocks 16.01**问题描述:将上一周“项目2-带武器的游戏角色”用“一个项目多个文件”的方式实现,其中两个类的声明           放在一个.h文件中,每个类的成员函数分别放到一个文件中,main()函数用一个文件。*程序输入;*程序输出:*/#include"shengming.h"int main(){    Role mary("Mary","red","TuLong",500,0,1,200);    Role jack("Jack","blue","YiTian",500,0,1,180);    cout<<"---begin---"<<endl;    mary.show();    jack.show();    cout<<"---1st round---"<<endl;    jack.attack(mary);    mary.show();    jack.show();    cout<<"---2nd round---"<<endl;    mary.attack(jack);    mary.show();    jack.show();    cout<<"---end---"<<endl;    return 0;}

运行结果:



知识点总结:

       该程序将不同的部分放在不同的文件里

学习心得:

       可提高程序的利用率


0 0
原创粉丝点击