gpt4 book ai didi

c++ - 如何使用 C++ 中的函数永久更改类属性值?

转载 作者:行者123 更新时间:2023-12-01 15:10:10 25 4
gpt4 key购买 nike

我用 C++ 编写了一个有 2 个类的程序。基本上“HeroList”只是“Hero”元素的 vector 。现在我想改变每个英雄给出的值(在函数“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) { //If 2 -> value + 1
if (value != 10) { //If value already 10 nothing happens
value = value + 1;
}

}
}

float getValue() {
return value;
}

string getName() {
return name;
}

void print() {
cout << name << ": " << value << endl;
}
};



class HeroList
{
private:
string name;
vector<Hero> Heroes;

public:
HeroList(string name = "std", vector<Hero> Heroes = {}) {

this->name = name;
this->Heroes = Heroes;
}

string getName() {
return name;
}

vector<Hero> getHeroes() {
return Heroes;
}

};



void change(Hero& x, Hero& y) { //Function to change the Hero-Values permanently (not only during the function is running)

x.setValue(2);
y.setValue(1);

}



int main() {

Hero Alice("Alice", 5);
Hero Bob("Bob", 5);

vector<Hero> duo = { Alice,Bob };

HeroList Duo("Duo", duo);

//try 1
change(Alice, Bob);
cout << "try 1: " << endl;

cout << Alice.getName()<<": " << Alice.getValue() << endl;
cout << Bob.getName() << ": " << Bob.getValue() << endl << endl;

//try 2
change(Duo.getHeroes()[0], Duo.getHeroes()[1]);

cout << "try 2: " << endl;
cout << Duo.getHeroes()[0].getName() << ": " << Duo.getHeroes()[0].getValue() << endl;
cout << Duo.getHeroes()[1].getName() << ": " << Duo.getHeroes()[1].getValue() << endl;

return 0;
}
输出:
try 1:
Alice: 6
Bob: 4

try 2:
Alice: 5
Bob: 5
应该如何:
try 1:
Alice: 6
Bob: 4

try 2:
Alice: 6
Bob: 4

最佳答案

您可以更新 getHeroes()返回对 Heroes 的引用 vector 来获得你想要的行为:

vector<Hero>& getHeroes() {
return Heroes;
}

关于c++ - 如何使用 C++ 中的函数永久更改类属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63706447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com