(1)基于下面设计的游戏中角色类,写出成员函数的实现。
#include<iostream>
#include<string>
using namespace std;
class Role
{
public:
void eat(int d); //吃东西,涨d血
void attack(); //攻击别人,涨1血
void beAttack(); //被攻击,失1血,血为0死掉
bool isAlived(); //是否活着
void setRole(string nam, int b); //设置
void show(); //显示
private:
string name;
int blood;
bool life;
};
void Role::eat(int d)//吃东西,涨d血
{
if(isAlived())
blood+=d;
}
void Role::attack()//攻击别人,涨1血
{
if(isAlived())
blood++;
}
void Role::beAttack()//被攻击,失1血,血为0死掉
{
if(isAlived())
blood--;
}
bool Role::isAlived() //是否活着
{
if(blood)
life=true;
else
life=false;
return life;
}
void Role::setRole(string nam, int b) //设置
{
name=nam;
blood=b;
}
void Role::show() //显示
{
cout<<name<<" has "<<blood<<" blood, it is ";
if(isAlived())
cout<<"alived"<<"."<<endl;
else
cout<<"dead"<<"."<<endl;
}
int main()
{
Role mary;
mary.setRole("Mary", 4);
mary.show();
mary.attack();
mary.eat(2);
mary.beAttack();
mary.beAttack();
mary.show();
return 0;
}
(2)设计构造函数,使角色对象在创建时被初始化;设计析构函数,当角色对象被撤消时,
提示一句“XXX(名称)退出江湖…”。可以用下面的代码进行测试,运行结果参考右图:
#include<iostream>
#include<string>
using namespace std;
class Role
{
public:
Role (string nam,int b);
~Role()
{
cout<<name<<" "<<"退出江湖..."<<endl;
}
void eat(int d); //吃东西,涨d血
void attack(); //攻击别人,涨1血
void beAttack(); //被攻击,失1血,血为0死掉
bool isAlived(); //是否活着
void setRole(string nam, int b); //设置
void show(); //显示
private:
string name;
int blood;
bool life;
};
Role::Role(string nam,int b)
{
name=nam;
blood=b;
}
void Role::eat(int d)//吃东西,涨d血
{
if(isAlived())
blood+=d;
}
void Role::attack()//攻击别人,涨1血
{
if(isAlived())
blood++;
}
void Role::beAttack()//被攻击,失1血,血为0死掉
{
if(isAlived())
blood--;
}
bool Role::isAlived() //是否活着
{
if(blood)
life=true;
else
life=false;
return life;
}
void Role::setRole(string nam, int b) //设置
{
name=nam;
blood=b;
}
void Role::show() //显示
{
cout<<name<<" has "<<blood<<" blood, it is ";
if(isAlived())
cout<<"alived"<<"."<<endl;
else
cout<<"dead"<<"."<<endl;
}
int main( )
{
Role mary("Mary", 4);
Role jack("Jack", 0);
mary.show();
jack.show();
return 0;
}
C++作业2-2
最新推荐文章于 2023-04-01 21:58:35 发布