为什么不保存变量中的更改

Why is not saving the changes in the variable?

本文关键字:保存 变量 为什么不      更新时间:2023-10-16

当谈到OOP时,我有点不知所措,所以我可能犯了一个错误,但我找不到它,这是代码中失败的部分:

util文件只是一个包含错误消息的文件

在main.cc:中

int main(){
 Ship imperialDestroyer(IMPERIAL);
 Ship rebelShip(REBEL);
 cout<<imperialDestroyer<<endl; //this just print the ship, you can ignore it
 cout<<rebelShip<<endl;
 imperialDestroyer.improveFighter(); //this is what fails
 cout<<imperialDestroyer<<endl;
}

在船.cc:

bool Ship::improveFighter(){
int num, cantidad, cost;
char option, respuesta;
bool improved = false;
cout << "Select fighter number: ";
cin >> num;
num = num-1;
if(num > this->fleet.getNumFighters() || num < 0)
  Util::error(WRONG_NUMBER);
else{
  cout << "What to improve (v/a/s)?";
  cin>>option;
if(option!='v' && option!='a' && option!='s')
  Util::error(UNKNOWN_OPTION);
else{
  cout << "Amount: ";
  cin >> cantidad;
  if(option == 'v')
cost = 2 * cantidad;
  else if(option == 'a')
cost = 3 * cantidad;
  else if(option == 's')
cost = (cantidad + 1) / 2;
  if(this->fleet.getCredits() < cost)
Util::error(NO_FUNDS);
  else{
cout << "That will cost you "<< cost <<" credits. Confirm? (y/n)";
cin >> respuesta;
if(respuesta == 'y'){
  this->fleet.improveFighter(num, option, cantidad, cost);
  improved = true;
}
  }
 }
}
return improved;
}

Flee.cc:

void Fleet::improveFighter(int nf, char feature, int amount, int cost){
  if(feature == 'v'){
    getFighter(nf).increaseVelocity(amount);
  }
  else if(feature == 'a'){
    getFighter(nf).increaseAttack(amount); 
  }
  else if(feature == 's'){
    getFighter(nf).increaseShield(amount);   
  }
}

}

在Fighter.cc:

Fighter Fleet::getFighter(int n) const{
  return fighters[n];
}
void Fleet::improveFighter(int nf, char feature, int amount, int cost){
  if(feature == 'v'){
    getFighter(nf).increaseVelocity(amount);
  }
  else if(feature == 'a'){
    getFighter(nf).increaseAttack(amount); 
  }
  else if(feature == 's'){
    getFighter(nf).increaseShield(amount);   
  }
}

出于某种原因,当我试图改进某些功能时,它不会被保存。

Fighter Fleet::getFighter(int n) const
{
  return fighters[n];
}

这将返回位于n位置的Fighter副本。修改副本不会影响原始副本。

您可以返回一个Fighter&(即引用),但由于您的函数是const,这将不起作用。您必须决定您希望此函数