【问题标题】:How to solve this error: Undefined reference to 'vtable for Enemy'? [duplicate]如何解决此错误:未定义对“敌人的 vtable”的引用? [复制]
【发布时间】:2020-02-03 17:08:41
【问题描述】:
#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”的引用。 我对派生类使用虚函数攻击,而 Enemy 是基类。

【问题讨论】:

  • Enemy,你的意思是virtual void attack() = 0;
  • 你没有定义virtual void attack();。要么添加=0 告诉编译器你没有打算定义它,要么定义它。

标签: c++ virtual-functions


【解决方案1】:

virtual void Enemy::attack(); 需要实现或应该是“纯抽象”:

class Enemy
{
    virtual void attack() = 0;
// ...
};

【讨论】:

  • 什么是::attack
  • @curiousguy:一个错字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多