【发布时间】:2020-12-21 16:14:48
【问题描述】:
我用 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) { //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返回一个向量。不是对 the 向量的引用,而是对 a 新向量的引用。 -
如果您想从课堂外访问和操作私有数据,为什么首先将其设为私有?你让它变得不必要地复杂
标签: c++ function class reference attributes