在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;
}


在Ship.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;
}


在Fleet.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];
}


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

您可以返回Fighter&(即引用),但是由于您的函数是const,因此无法正常工作。您将必须决定要将此功能设为什么。

关于c++ - 为什么不将更改保存在变量中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37299112/

10-12 22:21