*Copyright(c) 2016.煙臺大學計算機與控制工程學院
*ALL rights reserved.
*文件名稱:main.cpp
*作者:孫亞茹
*完成日期:2016年6月7日
*問題描述:與角色類相結合設計一個武器類。
*//
#include <iostream>
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();
};
void Wuqi::show()
{
cout<<"所用武器名字爲:"<<name<<" "<<"所屬系別是:"<<type<<" "<<"殺傷力是:"<<force<<endl;
}
int Wuqi::getForce()
{
return force;
}
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;
};
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;
}
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;
}
總結:
雖然程序複雜繁瑣,但只要耐下心去總結思考就一定能將程序寫的完滿。
考查了類的對象作爲另一個類的數據成員時的構造函數的寫法。
不利用繼承與派生一個類的數據成員的也能是另一個類的對象。