简体   繁体   中英

C++ - Changing class to use virtual functions

I am looking to make this more efficient, how would I Re-write the Enemy class to use inheritance and virtual functions? Including any new child classes.

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

This calculates how much total damage the band will dish out.

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

That's a good start, but with inheritance, you don't need to be so specific. For example, in the enemy class you have an attribute type . If you want to use inheritance, you don't need to specify the type , because the derived class would be the type .

As for your function getDamage() , you can leave it blank and turn it into a virtual function. Putting all of this together, your code should look something like this:

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

Notice how if you want to create another enemy, you just inherit from the Enemy class. And this way, you can store your characters in an array like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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