我正在制作一个pokemon战斗代码。以下是我制作的代码。首先,我定义了口袋妖怪类。
(pokemon.h(
class Pokemon{ ...
private:
int hp;
public:
int gethp();
void sethp(int n);
...}
(pokemon.cpp(
...
int Pokemon::gethp(){return hp;}
void Pokemon::sethp(int n){hp = n;}
...
接下来,我定义Trainer类。培训师有一份说教清单。
(培训师.h(
class Trainer: public Pokemon {
private:
Pokemon pokemons[3];
...
public:
Pokemon getpokemon(int n);
void setpokemons(int n, int m, int i);
...
(培训师.cpp(
Pokemon Pikachu(..., 160, ...) //Pikachu's hp is defined to be 160.
...
Pokemon makepokemon(int n) {
if (n == 1) { return Pikachu; }
....
}
Pokemon Trainer::getpokemon(int n) { return pokemons[n-1]; }
void Trainer::setpokemons(int n, int m, int i) {
pokemons[0] = makepokemon(n);
pokemons[1] = makepokemon(m);
pokemons[2] = makepokemon(i);
}
...
现在,当我在主函数中使用gethp/sethp时,我遇到了一个问题。
(主要部分(
Trainer me;
me.setpokemons(1, ...); // My first pokemon is pikachu then.
...
cout << me.getpokemon(1).gethp(); //This gives 160.
me.getpokemon(1).sethp(80); //I want to change Pikachu's hp into 80.
cout << me.getpokemon(1).gethp(); //Still this gives 160.
问题是sethp不起作用。我想我需要在某个时候使用引用调用来解决这个问题,但我不知道该怎么做。
如何解决此问题?
me.getpokemon(1).sethp(80)
让我们来了解一下——您正在调用me.getpokemon(1)
,它从me
的pokemons
数组返回一个Pokemon
的副本。然后在副本上调用sethp
,将其hp
设置为80。然后,由于副本没有保存在任何地方,在它被销毁之前,你永远不会再看到它。。。
相反,您想要的是使getpokemon(1)
返回对副本的pokemons
项insetad的引用,这样当您调用sethp()
时,您就修改了原始项。您可以通过更改函数来返回引用而不是副本:
Pokemon& Trainer::getpokemon(int n) { return pokemons[n-1]; }
// ^^^