我用 C++ 编写了一个包含 2 个类的程序。基本上“HeroList”只是“Hero”元素的向量。现在我想更改每个英雄给出的值(在函数“change”中)。但这不起作用。仅当我直接使用“英雄”对象作为参数调用该函数时,它才有效(尝试 1)。但是当我使用“heroList”元素作为参数(尝试2)时,它仅在函数处于活动状态期间更改值,并且当其结束时它们会重置。我猜这与引用的使用有关,但我找不到我的错误。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Hero
{
private:
string name; //Hero-Name
int value; //Hero-Value
public:
Hero(string name = "std", int value = 0) {
this->name = name;
this->value = value;
}
void setValue(int i) {
if (i == 1) { //If 1 -> value - 1
if (value != 0) { //If value already 0 nothing happens
value = value - 1;
}
}
if (i == 2) { …Run Code Online (Sandbox Code Playgroud)