我是c++ n00b,我不确定是否在正确的位置查看,但对此感到困惑:

include <iostream>

using namespace std;

class Enemy
{
    public:
        void sayHere()
        {
            cout<<"Here"<<endl;
        }
        virtual void attack()
        {
        }
};

class Monster: public Enemy
{

    public:
        virtual void attack()
        {
            cout<<"RAWR"<<endl;
        }

};

class Ninja: public Enemy
{

    public:
        virtual void attack()
        {

            cout<<"Hiya!"<<endl;
        }
};

int main()
{
    Ninja n;
    Monster m;
    Enemy enemies[2];
    enemies[0] = m;
    enemies[1] = n;

    for(int i = 0; i<2; i++)
    {
        enemies[i].sayHere();
        enemies[i].attack();//Will not be overriden
    }
    return 0;
}

我的问题是,为什么不重写Monster或Ninja类中的Attack()函数?任何帮助,甚至链接,将不胜感激。

最佳答案

这与您不通过指针访问敌人有关:

    Ninja n;
    Monster m;

    Enemy *enemies[2];

    enemies[0] = &m;
    enemies[1] = &n;

    for (int i = 0; i < 2; i++)
    {
        enemies[i]->sayHere();
        enemies[i]->attack();
    }
    return 0;

关于c++ - 对虚拟函数C++感到困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6881167/

10-10 13:10