繁体   English   中英

C++ - 更改 class 以使用虚拟功能

[英]C++ - Changing class to use virtual functions

我希望提高效率,我将如何重写 Enemy class 以使用 inheritance 和虚拟功能? 包括任何新的子类。

class Enemy
{
public:
    int type; // 0 = Dragon, 1 = Robot
    int health; // 0 = dead, 100 = full
    string name;
    Enemy();
    Enemy(int t, int h, string n);
    int getDamage(); // How much damage this enemy does
};
Enemy::Enemy() : type(0), health(100), name("")
{ }
Enemy::Enemy(int t, int h, string n) :
    type(t), health(h), name(n)
{ }
int Enemy::getDamage() {
    int damage = 0;
    if (type == 0) {
        damage = 10; // Dragon does 10
        // 10% change of extra damage
        if (rand() % 10 == 0)
            damage += 10;
    }
    else if (type == 1) {
        // Sometimes robot glitches and does no damage
        if (rand() % 5 == 0)
            damage = 0;
        else
            damage = 3; // Robot does 3
    }
    return damage;
}

这计算了乐队将造成的总伤害。

int calculateDamage(vector<Enemy*> bandOfEnemies)
{
    int damage = 0;
    for (int i = 0; i < bandOfEnemies.size(); i++)
    {
        damage += bandOfEnemies[i]->getDamage();
    }
    return damage;
}

这是一个好的开始,但是对于 inheritance,您不需要那么具体。 例如,在敌人 class 中,您有一个属性type 如果要使用 inheritance,则不需要指定type ,因为派生的 class 将是type

至于您的 function getDamage() ,您可以将其留空并将其变为虚拟 function。 将所有这些放在一起,您的代码应如下所示:

class Enemy
{
public:
    int health; // 0 = dead, 100 = full
    string name;

    Enemy();
    Enemy(int t, int h, std::string n);

    virtual int getDamage() = 0; // pure virtual function
};

Enemy::Enemy()
    : type(0), health(100), name("") {}

Enemy::Enemy(int t, int h, std::string n)
    : type(t), health(h), name(n) {}


// class 'Dragon' inherits from class 'Enemy'
class Dragon : public Enemy
{
public:
    Dragon() {}

    int getDamage()
    {
        // dragon's damage
    }
};

请注意,如果您想创建另一个敌人,您只需从Enemy class 继承即可。 这样,您可以将字符存储在这样的数组中:

vector<Enemy> enemies = {
    Dragon(),
    Dragon(),
    Robot()
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM