【发布时间】: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