给出以下示例:
// Fighter.h
class Fighter {
public:
void attack(Fighter * other);
protected:
Fighter(const std::string nick) : nickname(nick) { };
virtual void atk(Fighter * other) = 0;
const std::string nickname;
};
// Fighter.cpp
#include "Fighter.h"
void Fighter::attack(Fighter * other) {
std::cout << nickname << " attacks " other->getNickname() << std::endl;
atk(other);
}
// Warrior.cpp : Fighter
void Warrior::atk(Fighter * other) {
int dmg = rand() % off;
int chance = rand() % 6;
if (chance == 3) {
dmg += dmg;
std::cout << nickname << ": Double Damage!";
}
other->hit(dmg);
if (!other->isDead()) {
other->counter(this);
}
}
// main.cpp
#include "Fighter.h"
#include "Warrior.h"
Fighter * a = new Warrior(string("A"));
Fighter * b = new Warrior(string("B"));
a->attack(b); // << LINKER ERROR
我只能做到这一点:
未定义参考“战斗机::攻击(战斗机*)&#39;
换句话说,我想要一个处理所有派生类的输出的基本方法,所以我不必复制每个子类中的代码?