【问题标题】:c++ nested class getter and setter does not workc ++嵌套类getter和setter不起作用
【发布时间】:2020-10-15 13:13:23
【问题描述】:

我正在制作口袋妖怪战斗代码。这是我制作的代码。 首先,我定义了 Pokemon 类。

(pokemon.h)

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

(口袋妖怪.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 不工作。我想我需要在某些时候使用引用调用来解决这个问题,但我不知道该怎么做。

我该如何解决这个问题?

【问题讨论】:

  • 请发布真实代码,minimal reproducible example。当我们想帮助您编写真正的代码时,您通过到处引入语法错误而造成的错误代码几乎没有用处。
  • 你在正确的轨道上,但你不需要 call 引用,你需要 return 引用。 (虽然我认为带有increaseHpdecreaseHp 的界面会更好。getter 和setter 并不好。)
  • class Trainer: public Pokemon { 如果Trainer 继承自Pokemon,您的意思是说训练家口袋妖怪。这是正确的吗?
  • 对不起,我的真实代码包含其他许多信息,所以它很长。所以我只发布了最少量的内容。
  • @MoonJuHong 如果 Trainer 不是 Pokemon,那么它不应该从 Pokemon 继承。在此处阅读有关“is-a”与“has-a”的更多信息:stackoverflow.com/a/36162730/2602718

标签: c++


【解决方案1】:
me.getpokemon(1).sethp(80)

让我们来看看这个——你正在调用me.getpokemon(1),它会从mepokemons 数组中返回一个Pokemon 的副本。然后您在副本上调用sethp,将其hp 设置为80。然后,由于副本没有保存在任何地方,您将再也看不到它,直到它被销毁...

您想要的是让getpokemon(1) 返回一个引用 到副本的pokemons 项插入,这样当您调用sethp() 时,您正在修改原来的。您可以通过更改函数以返回引用而不是副本来做到这一点:

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

【讨论】:

  • 哦,我以前的方式没有任何改变。好的,现在我得到的不是副本,而是它的参考,以便我可以更改它们。现在我看到了图片。感谢您的清晰解释!
猜你喜欢
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 2015-01-20
相关资源
最近更新 更多