c++ - 无法访问地址 0x1 处的内存
问题描述
我有三个基类 {Player,Weapon,Game} 和一个从 Player 继承的 Class Warrior。我添加的代码可能不是最少的,但我添加了任何相关的内容。因为不知道去哪里找。
这是我对简单调试的测试,我将 Players 添加到在 game.h 中定义的 vectorPlayers
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;
}
当我到达第 4 行时,vectorPlayers[0] 包含正确的输入。但是当我进入game.cpp并在addWarrior中调用函数addPlayer时,例如players_name突然切换到 错误:Cannot access memory at address 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){
}
解决方案
推荐阅读
- python - 如何继续循环直到满足条件?
- python - 从通过树莓上的 cron 运行的 python 脚本恢复打印输出
- java - Selenium:在获取 DOM 元素列表后查找子标签
- javascript - 在 Vanilla JS 中使用数据属性添加/删除类
- javascript - 单击按钮时出现错误
- ubuntu - 我的 HTTPS (SSL/TLS) nginx 配置给了我超时
- supabase - 如何在 Supabase 中使用 join 进行查询?
- python - Django html table - 如何指定/定位某个单元格?
- r - 从 R 中的包“mcp”输出中绘制 50% 分位数和可信区间
- database - 根据时间戳 Kusto Query 删除重复项