Pregunta

So I made this simple program:

#include <iostream>
using namespace std;

class Enemy{
public:
    virtual void attack(){}
    int attackPower;
        void setAttackPower(int a)
        {
            attackPower = a;
        }
};

class Ninja: public Enemy{
public:
    void attack(){
        cout<<"ninja  "<< attackPower<<endl;
    }
};

class Monster: public Enemy{

    public:
    void attack(){
        cout<<"monster  "<< attackPower<<endl;
    }
};


int main()
{
    Ninja n;
    Monster m;
    Enemy *enemy1= &n;
    Enemy *enemy2 = &m;
    enemy1->attack();
    enemy2->attack();
    enemy1->setAttackPower(29);
    enemy2->setAttackPower(99);

    return 0;
}

And the problem I'm having is that when I print out the attack power for like enemy1 it's not what I set it to, 29, its some huge number. So what I'm wondering is why is that number huge number occurring and how can I fix it?

¿Fue útil?

Solución

Initialise attackpower first by

enemy1->setAttackPower(29); enemy2->setAttackPower(99);

Then print them,

enemy1->attack(); enemy2->attack();

The main would be like

int main()
{
    Ninja n;
    Monster m;
    Enemy *enemy1= &n;
    Enemy *enemy2 = &m;

    enemy1->setAttackPower(29); // set the attack power first
    enemy2->setAttackPower(99);
     enemy1->attack();          // then print it otherwise junk values will be printed
    enemy2->attack();
    return 0;
}

Otros consejos

You called attack() before setAttackPower(). Because you did not initialize either m or n, they have garbage values.

It's been a quite a while since I wrote any C++ but does this code:

void attack(){
    cout<<"monster  "<< attackPower<<endl;
}

also need to the virtual keyword:

virtual void attack(){
    cout<<"monster  "<< attackPower<<endl;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top