gpt4 book ai didi

c++ - 为什么不保存变量中的更改?

转载 作者:行者123 更新时间:2023-11-28 05:40:06 25 4
gpt4 key购买 nike

我对 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];
}

这将返回位置 n 处的 Fighter拷贝。修改拷贝不会影响原件。

您可以返回一个Fighter&(即一个reference),但是因为您的函数是const,所以这将不起作用。您将必须决定您希望此功能成为什么

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com