当涉及到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);
}
}
由于某种原因,当我尝试改进某些功能时,它不会被保存。
答案 0 :(得分:1)
Fighter Fleet::getFighter(int n) const
{
return fighters[n];
}
这将返回位置Fighter
的{{1}}的副本。修改副本不会影响原件。
您可以返回n
(即引用),但由于您的函数为Fighter&
,因此无效。你将不得不决定你想要这个函数 。