You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++对象combatStats数组方法执行后值重置问题求助

问题分析与解决:Hp值修改后自动恢复的原因

核心问题

你的chooseMove方法参数用的是传值调用(GameEntity target),这会在调用时创建目标对象的副本。你在方法里调用target.damage()修改Hp时,实际改的是这个临时副本的属性,方法执行完副本就销毁了,原对象的Hp自然不会有变化——这就是为什么看起来Hp被修改后又恢复了初始值。

解决方案

1. 将参数改为引用类型

把chooseMove的参数改成引用传递(GameEntity& target),这样操作的就是原对象本身,不会产生拷贝。修改两处代码:

基类GameEntity的chooseMove方法:

void chooseMove(GameEntity& target, int round){
    cout << name << " health: " << combatStats[Hp] << '\n';
    blockVal = 0;
    if(round%2 == 0){
        cout << name << ": does a slash attack." << '\n';
        target.damage(10 , GameType::slash);
    }
    else if(round == 5 || round == 12){
        heal(5, GameType::light);
    }
    else{
        block(8);
    }
}

Player类的chooseMove方法:

void chooseMove(GameEntity& target, int round){
    cout << name << " health: " << combatStats[Hp] << '\n';
    blockVal = 0;
    cout <<"System: what do you want to do?" << '\n';
    cout <<"1) slash attack" << '\n';
    cout <<"2) punch" << '\n';
    cout <<"3) riposte" << '\n';
    cout <<"4) heal" << '\n';
    cout <<"5) block" << '\n';
    string input;
    cin >> input;
    switch (stoi(input))
    {
    case 1:
        cout << name << ": does a slash attack." << '\n';
        target.damage(10 , GameType::slash);
        break;
    case 2:
        cout << name << ": punches " << target.getName() << " really hard"<< '\n';
        target.damage(4 , GameType::bludgeon);
        block(2);
        break;
    case 3:
        cout << name << ": hits " << target.getName() << " and retracts, really fast"<< '\n';
        target.damage(7, GameType::thrust);
        block(5);
        break;
    case 4:
        cout << name << ": channels the light element"<< '\n';
        target.damage(7, GameType::thrust);
        heal(4, GameType::light);
        break;
    case 5:
        block(12);
    
    default:
        break;
    }
}

2. 额外优化建议

  • 把combatStats的访问权限改回protected,符合C++封装原则,不要暴露公共成员变量。
  • 修正拼写错误:isAllive应该是isAlive,虽然不影响运行,但代码规范很重要。
  • 释放动态分配的内存,避免内存泄漏:在main函数末尾添加:
    delete opponent;
    delete player;
    

内容的提问来源于stack exchange,提问作者Mighty Dragon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:09:53