C++ 对基函数的未定义引用
给出以下示例:C++ 对基函数的未定义引用,c++,C++,给出以下示例: // 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.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
//Fighter.h
职业拳击手{
公众:
无效攻击(战斗机*其他);
受保护的:
战士(const std::string nick):昵称(nick){};
虚拟空位atk(战斗机*其他)=0;
常量std::字符串昵称;
};
//战斗机
#包括“Fighter.h”
无效战斗机::攻击(战斗机*其他){
标准::cout攻击(b)//@NathanOliver再次阅读,基本攻击
应该在派生计算的实际atk
发生之前打印一条消息,否则攻击
方法中的cout
将在每个子类中重复。在公共部分中错过了攻击。有关链接问题,请参阅此s、 @NathanOliver再次读取,基本attack
应该在派生计算的实际atk
发生之前打印一条消息,否则attack
方法中的cout
将在每个子类中重复。错过了公共部分中的攻击。有关链接问题,请参阅此。