问题及代码:
/*
* Copyright (c) 2016,烟台大学计算机与控制工程学院
* All rights reserved.
* 文件名称:main.cpp
* 作 者:赵志君
* 完成日期:2016年3月27日
* 版 本 号:v1.0
*
* 问题描述:补充完整成员函数,使角色能一定的行动或改变状态
*/
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
class Role
{
public:
void setRole(string ,int);
void show();
void attack(int );
void eat(int );
void beAttack(int );
private:
string name;
int blood;
};
void Role::setRole(string nam,int n) //角色创建,名字命名,血量设置
{
name=nam;
blood=n;
}
void Role::show() //展现角色当前状态
{
cout<<"角色名: "<<name<<" 剩余血量: "<<blood<<endl;
if(blood>0)
cout<<"alived"<<endl;
else
cout<<"dead"<<endl;
}
void Role::attack(int n) //攻击他人
{
blood=blood+n;
}
void Role::eat(int n) //吃东西加血
{
switch(n)
{
case 0: blood=blood+1;
case 1: blood=blood+2;
case 2: blood=blood+3;
}
}
void Role::beAttack(int n) //被人攻击失n血
{
blood=blood-n;
}
int main()
{
srand(time(0));
Role mary;
mary.setRole("Mary",20);
mary.show();
mary.attack(rand()%2);
mary.eat(rand()%3);
mary.beAttack(rand()%5);
mary.beAttack(rand()%5);
mary.show();
return 0;
}
运行结果: