为什么不保存变量中的更改
Why is not saving the changes in the variable?
当谈到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
,这将不起作用。您必须决定您希望此函数为。
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 无法通过头文件保存变量的值
- 一个变量的输入值也会保存到另一个变量中
- 是否可以在C++变量中保存多种类型的枚举?
- 如何在 c++ 中创建一个可以将自身保存为变量的类?
- 可视化C++从文件中保存/读取多个变量
- 将数据从 SQLite 数据库保存到变量中
- C++我应该用什么来保存格式化为字符串变量(如sprintf())的文件
- 指向结构变量的指针未保存到eeprom
- (C++)for循环中的空初始语句是否保存所有编译器中变量的上一次初始化
- 让类方法为每个实例保存不同的静态变量
- 在没有外部文件的情况下在应用会话之间保存变量
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 从多个类中保存变量
- 从保存变量数据类型的数据结构中检索值,而不指定返回类型
- 在程序关闭后,是否可以在内部保存变量并读/写入
- 为什么不保存变量中的更改
- 如何使用Q设置保存变量
- 如何在RAM中安全地保存c++变量
- 需要帮助关于通过fstream保存变量,我需要使用向量