#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”的未定义引用。我对派生类使用虚函数攻击,而敌人是基类。
class Enemy
{
virtual void attack() = 0;
// ...
};