如何解决此错误:对“ vtable for Enemy”的未定义引用? [重复]

问题描述 投票:0回答:1
#include <iostream>
using namespace std;
class Enemy{// step 1
public:
virtual void attack(); //now every enemy has the ability to attack. We know that every specific class (Ninja and monster have their own attack function).
 void setattackpower(int a){ attvar=a;};
protected:
    int attvar;
            };   //We have to use Virtual on order to avoid overwriting the function. Any class which inherits a virtual function is called a polymorphic class.

class Ninja: public Enemy{ //step 2 code the function for each derived class
public:
    void attack(){
    cout << "ninja attack!-" << attvar<<endl;
    }
};
class Monster: public Enemy{
public:
    void attack(){
    cout << "Monster attack!-" <<attvar<<endl;
    }
};
int main(){// step 3
 Ninja n;
 Monster m;
 n.setattackpower(29);
 m.setattackpower(99);
Enemy *enemy1=&n;
Enemy *enemy2=&m;
enemy1->attack();
enemy2->attack();
};

错误:对“ vtable for Enemy”的未定义引用。我对派生类使用虚函数攻击,而敌人是基类。

c++ virtual-functions
1个回答
1
投票
class Enemy { virtual void attack() = 0; // ... };
© www.soinside.com 2019 - 2024. All rights reserved.