这个极其简单的攻击游戏(对我来说)的主要价值是让自己熟悉简单的多态性,并练习使用指针。话虽如此,我很想补充一下。查看我的程序,我不确定是否应该创建一个单独的“Hero”类,并且只是从“Character”类继承,或者我是否应该假设 Hero 是“Character”类,敌人继承的。我现在唯一想做的就是实现英雄在攻击后的生命值降低的东西。抱歉,如果它非常初级,我只是想了解基础知识。
谢谢。
#include <iostream>
#include "Character.h"
using namespace std;
int main() {
Ninja n;
Dragon d;
Character *enemy1 = &n;
Character *enemy2 = &d;
enemy1->setAttackPower(20);
enemy2->setAttackPower(40);
n.attack();
d.attack();
return 0;
}
//Character.h
#include <iostream>
using namespace std;
class Character
{
protected:
int Health = 100;
int attackpower;
public:
void setAttackPower(int attack) {
attackpower = attack;
}
};
class Ninja: public Character
{
public:
void attack() {
cout << "Ninja attacks your character! - " << attackpower << " Points!" << endl;
}
};
class Dragon: public Character
{
public:
void attack() {
cout << "Dragon attacks your character! - " << attackpower << " Points!" << endl;
}
};