我有一个角色类和两个子类战士和巫师。
class Character {
protected:
std::string m_name;
Weapon m_weapon;
int m_life;
public:
virtual void hit(Character& cible);
};
class Warrior : public Character{
public:
Warrior(std::string name);
};
class Wizard : public Character{
public:
Wizard(std::string name);
};
我也有一个类武器。
class Weapon {
protected:
std::string m_name;
int m_damage;
public:
Weapon();
Weapon(std::string name,int damage, int reloading_time);
int get_damage() ;
};
命中函数为:
void Character::hit(Character &cible){
cible.dec_life(m_weapon.get_damage());
}
get_damage 很简单:
int Weapon::get_damage() {
return m_damage;
}
问题是 m_weapon.get_damage() 在 hit 函数中为每个角色(战士或法师)返回值 -2,即使其武器的伤害是 10 或 15。
主要的:
int main()
{
string character_name;
cout << "Warrior 1 : ";
cin >> character_name;
Warrior character_1(character_name);
cout << endl << "Wizard 2 : ";
cin >> character_name;
Wizard character_2(character_name);
character_1.hit(character_2);
}
武器制造商:
Weapon::Weapon(std::string name,int damage, int reloading_time){
m_name=name;
m_damage=damage;
}
战士构造器:
Warrior::Warrior(string name){
m_name=name;
m_life=100;
Weapon m_weapon("Rusted Axe",5,0);
cout << endl << "Warrior " << m_name <<" created." <<endl;
}
向导构造函数:
Wizard::Wizard(string name){
m_name=name;
m_mana=100;
m_life=100;
Weapon m_weapon("Apprentice Wand",10,0);
cout << endl <<"Wizard " << m_name <<" created."<<endl;
}
知道我哪里弄错了吗?