【问题标题】:C++ - Changing class to use virtual functionsC++ - 更改类以使用虚函数
【发布时间】:2020-04-30 01:03:27
【问题描述】:

我希望提高效率,如何重写 Enemy 类以使用继承和虚函数?包括任何新的子类。

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;
}

【问题讨论】:

  • 是的,继承、虚函数和多态一般来说似乎是一个不错的选择。
  • 在决定接口之前 - 你应该首先弄清楚你需要什么。如果你只有一个 Enemy 类型,那么就不需要任何东西。如果你想要各种各样的 Enemy 类而不是找出哪些方法可能不同然后虚拟化。

标签: c++ inheritance virtual-functions


【解决方案1】:

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

至于你的函数getDamage(),你可以留空,把它变成一个虚函数。将所有这些放在一起,您的代码应如下所示:

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 类继承即可。这样,您可以将字符存储在这样的数组中:

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

【讨论】:

  • 你展示的那个向量会导致object slicing和调用抽象基函数时的异常。要使多态在 C++ 中工作,您需要有指针或引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
  • 2010-09-18
  • 2015-06-23
  • 2021-01-26
  • 1970-01-01
相关资源
最近更新 更多