main.cpp
#include<iostream> #include"shengming.h" using namespace std; int main() { Role James("james",8,2,"east","Man","TULONG",2); Role Curry("curry",7,3,"west","Feman","YITIAN",3); James.show(); Curry.show(); Curry.attack(James); James.beAttack(Curry); James.eat(5); James.attack(Curry); James.range1(); Curry.range1(); James.show(); Curry.show(); return 0; }
shengming.h
#ifndef SHENGMING_H_INCLUDED #define SHENGMING_H_INCLUDED using namespace std; class Weapon { public: Weapon(string wnam, int f); int getForce(); void setdata(); void showdata(); private: string wname; //名称 int force; //威力 }; class Role { public: Role(string name,int blo,int ran,string nati,string se,string wnam,int forc);//构造函数 ~Role(); void show(); void attack(Role&r); void eat(int medicine); void beAttack(Role&r); void range1(); private: string name; int blood; bool life; int range; string nation; string sex; Weapon weapon; }; #endif // SHENGMING_H_INCLUDED
weapon.cpp
#include<iostream> #include"shengming.h" using namespace std; Weapon::Weapon(string wnam, int forc):wname(wnam),force(forc) {} int Weapon::getForce() { return force; } void Weapon::setdata() { std::cout << "请输入武器的名字、威力:" << std::endl; std::cin >> wname >> force; } void Weapon::showdata() { std::cout<<"武器名称 "<<wname <<"威力 "<<force<<std::endl; }
role.cpp
#include<iostream> #include"shengming.h" using namespace std; Role::Role(string nam,int blo,int ran,string nati,string se,string wnam,int forc):name(nam),blood(blo),range(ran),nation(nati),sex(se),weapon(wnam,forc) { if(blood>0) life=true; else life=false; } Role::~Role() { std::cout<<name<<"已经退出江湖..."<<std::endl; } void Role::show() { cout<<name << "has" << blood << "blood " <<range << "级 " <<nation << "族 " <<sex <<endl; if(blood>0) life=true; else life=false; weapon.showdata(); } void Role::attack(Role &r) { blood+=weapon.getForce(); r.blood-=weapon.getForce(); if(r.blood<=0) r.life=false; } void Role::beAttack(Role&r) { blood-=weapon.getForce(); r.blood+=weapon.getForce(); if(blood<=0) life=false; } void Role::eat(int medicine) { blood+=medicine; } void Role::range1() { if(blood>=10) range+=1; }
运行结果: