简体   繁体   English

C++ 嵌套类 getter 和 setter 不起作用

[英]c++ nested class getter and setter does not work

I'm making a pokemon battle code.我正在制作口袋妖怪战斗代码。 Here are codes that I've made.这是我制作的代码。 First, I define Pokemon class.首先,我定义 Pokemon 类。

(pokemon.h) (口袋妖怪.h)

class Pokemon{ ... 
private:
    int hp;
public:
    int gethp();
    void sethp(int n); 
...}

(pokemon.cpp) (口袋妖怪.cpp)

... 
int Pokemon::gethp(){return hp;}
void Pokemon::sethp(int n){hp = n;} 
...

Next, I define Trainer class.接下来,我定义 Trainer 类。 Trainer has a list of pokemons.训练师有一个口袋妖怪列表。

(trainer.h) (培训师.h)

class Trainer: public Pokemon {
private:
    Pokemon pokemons[3];
...
public:
    Pokemon getpokemon(int n);
    void setpokemons(int n, int m, int i);
...

(trainer.cpp) (教练.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);
}
...

Now, when I use gethp/sethp in the main fucntion, I have a problem.现在,当我在主要功能中使用 gethp/sethp 时,我遇到了问题。

(main part) (主要部分)

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.

The problem is that sethp is not working.问题是 sethp 不起作用。 I guess that I need to use call by reference at some point to fix this, but I don't get how I should do.我想我需要在某个时候使用引用调用来解决这个问题,但我不知道该怎么做。

How can I fix this problem?我该如何解决这个问题?

me.getpokemon(1).sethp(80)

Let's walk through this--you're calling me.getpokemon(1) , which returns a copy of a Pokemon from me 's pokemons array.让我们来看看这个——你正在调用me.getpokemon(1) ,它从mepokemons数组中返回一个Pokemon的副本。 You then call sethp on the copy, setting its hp to 80. And then, since the copy isn't saved anywhere, you never see it again until it's destroyed...然后你在副本上调用sethp ,将它的hp设置为 80。然后,由于副本没有保存在任何地方,你永远不会再看到它,直到它被销毁......

What you want instead, is to cause getpokemon(1) to return a reference to the pokemons item insetad of a copy, so that when you call sethp() , you're modifying the original.你想,而不是什么,是导致getpokemon(1)返回一个参考pokemons的复制项insetad,这样,当你调用sethp()你修改原始。 You can do that by changing the function to return a reference instead of a copy:您可以通过更改函数以返回引用而不是副本来做到这一点:

Pokemon& Trainer::getpokemon(int n) { return pokemons[n-1]; }
//    ^^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM