我有3个基础职业{Player,Weapon,Game}和1个从Player继承的Class Warrior。我添加的代码可能不是最少的,但是我添加了所有可能相关的内容。因为我不知道要看哪里。
这是我进行简单调试的测试,我在game.h中定义的vectorPlayers中添加了Players
int main() {
Weapon w1("hello",STRENGTH,3);
Game game(3);
game.addWarrior("s22","we",STRENGTH,3,55);
//4
game.addWarrior("s22","we",STRENGTH,3,55);
return 0;
}
当我到达第四行时,vectorPlayers [0]包含正确的输入。但是当我进入game.cpp并在addWarrior中调用函数addPlayer时,例如players_name突然切换为 错误:无法访问地址0x1处的内存
//inside game.cpp
GameStatus Game::addPlayer(const string playerName, const string weaponName,
Target target,int hit_strength)
{
Weapon newWeapon(weaponName,target,hit_strength);
Warrior newWarrior(playerName,newWeapon,false);
if(ifNameAlreadyExists(playerName)) {
addRegPlayer(static_cast<Player*>(&newWarrior));
}
return SUCCESS;
}
GameStatus Game::addRegPlayer(Player* player)
{
playersVector.push_back(player);
}
//base classes
class Game {
private:
int maxPlayer;
vector<Player*> playersVector;
}
class Player {
string player_name;
int level;
int strength;
Weapon player_weapon;
protected:
int place;
int life;
public:
Player(const string &name, const Weapon &weapon);
virtual ~Player();
}
//inherited class
class Warrior : public Player {
private:
bool rider;
public:
Warrior ();
Warrior (string const& name, Weapon const& weapon, bool rider);
~ Warrior () override = default;
Warrior &operator=(const Warrior &warrior) ;
Warrior ( const Warrior &warrior) = default;
void makeStep() override;
};
//Constructor of Warrior
Warrior::Warrior(string const& name, Weapon const& weapon, bool rider) :
Player(name,weapon),rider(rider){
if (weapon.getTarget() == LEVEL){
throw IllegalWeapon();
}
}
//constructor of player
Player::Player(const string& name, const Weapon& weapon) :
level(1),life(1),strength(1),player_weapon(weapon),player_name(name),place(0){
}