2016-05-18 15 views
0

私はOOPに関して何とかしているので、おそらく間違いをしていますが、見つけることができません。ここでは失敗するコードの一部があります:変数に変更を保存しないのはなぜですか?

utilファイルは単なるShip.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; 
} 

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

エラーメッセージmain.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

インデントを修正できますか?あなたの[MCVE]を提示してください。 –

+0

'cout << imperialDestroyer << endl;' - これはコンパイルされていますか?はいの場合は、関連するコードを表示してください。 – Ajay

+0

@Ajay:どうしてですか?それはどのように問題に関連していますか? –

答えて

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

これは位置nFighterコピーを返します。コピーを変更してもオリジナルには影響しません。

Fighter&参照)を返すことができますが、機能がconstであるため機能しません。あなたはこの機能をにしたいものを決める必要があります。です。

+1

私はベクトル戦闘機を使用しなければならなかったことを認識した "元のものに影響を与えないコピーを修正する"というヒントのおかげで、getFighterモジュールを使用してはいけませんでした。それを見てください。 – Sefean

+0

@Sefean:Great :) –