如何通过函数修改C++对象属性?RPG角色HP修改失效问题
问题分析与解决方法
你的代码有两个核心问题导致HP未被修改:
- 数组存储的是对象副本:
main里创建的Final和Fantasy对象,被复制到Player数组中,数组里的是独立副本而非原对象。Battle函数修改的是副本的HP,原对象Final的HP自然不会变化。 - 函数返回值不符合语法:
Battle声明为int类型却无返回值,会触发未定义行为,应改为void。
以下是两种可行的修改方案:
方案一:用指针数组存储原对象地址
让数组直接关联原对象,修改时操作的就是原对象的HP:
#include <iostream> #include <string> class Chara { public: int HP; Chara(int health) { HP = health; } }; // 修改参数为指针数组,返回值改为void void Battle(Chara* Party[2]) { // 通过指针直接修改原对象HP Party[0]->HP -= 2; } int main() { Chara Final(0); Chara Fantasy(7); // 数组存储原对象的地址 Chara* Player[2] = {&Final, &Fantasy}; Battle(Player); std::cout << Final.HP; // 输出-2,原对象HP已修改 }
方案二:用std::vector存储引用包装器(现代写法)
避免直接用指针,用std::reference_wrapper存储对象引用:
#include <iostream> #include <string> #include <vector> #include <functional> // 用于std::reference_wrapper class Chara { public: int HP; Chara(int health) { HP = health; } }; void Battle(std::vector<std::reference_wrapper<Chara>>& Party) { // 获取引用并修改HP Party[0].get().HP -= 2; } int main() { Chara Final(0); Chara Fantasy(7); // 存储对象的引用 std::vector<std::reference_wrapper<Chara>> Player = {Final, Fantasy}; Battle(Player); std::cout << Final.HP; // 输出-2 }
额外说明
如果你的需求是让数组里的角色为独立对象(无需关联原Final和Fantasy),只需修改输出语句为数组内角色的HP即可:
// main中替换输出语句 std::cout << Player[0].HP;
这种情况下数组副本的HP确实已被修改,只是你之前输出的是原对象的HP所以看不到变化。
内容的提问来源于stack exchange,提问作者Structurely Sound
相关产品推荐
相关产品推荐

