用多个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; }