简体   繁体   中英

C++ When i call a method from the method of another class it works but doesn't edit the first method's class' variables

As title says, i have this code here

#include <iostream>
#include <string>
using namespace std;

class SpaceShip{
public:
    int fuel;
    SpaceShip(int f){
        this->fuel=f;
    }
    bool ConsumeFuel(int f){
        cout<<"Consuming "<<f<<" fuel\n";
        if (this->fuel<f){
            this->fuel=0;
            cout<<"Out of Fuel\n";
            return false;
        }
        else{
            this->fuel=this->fuel-f;
            if (this->fuel==0){
                cout<<"Out of Fuel\n";
            }
            return true;
        }
    }
    void PrintResources(){
        cout<<"Available: "<<this->fuel<<"\n\n";
        return;
    }
};

class MissionSelector{

public:
    bool select(SpaceShip sps){
        while(true){

            cout<<"Choose exploration\n\n";
            string id;
            cin>>id;
            if(id=="exploration"){
                return this->exploration(sps);
            }
            else{
                cout<<"No valid id selected!\n";
            }

        }
    }
private:
    bool exploration(SpaceShip sps){
        bool result=sps.ConsumeFuel(20);
        if (result){
            cout<<"Mission completed correctly!\n\n";
        }
        else{
            cout<<"Mission Failed, not enough resources!\n\n";
        }
        return result;
    }

};
int main(){

    MissionSelector selector;
    SpaceShip sps(100);
    sps.ConsumeFuel(20);
    bool end=false;
    int score=0;
    while(!end){
        sps.PrintResources();
        if(selector.select(sps)){
            score++;
        }
        else{
            end=true;
        }
    }
    return 0;
}

When i call ConsumeFuel(x) frome the main it edits the object's fuel variable just fine, when i do it from the exploration method of the MissionSelector class (which i call in the select method of the MissionSelector, which is called in the main) it returns true but never edits the fuel variable.

There are other parts of the code i omitted since it's just other details not really helping in finding out the bug which is here, it's mostly other resources and other missions. And stackoverflow keeps telling me there are not enough details since it's mostly code but it's really everything here, nothing more i'll add this couple of lines to make it happy.

Can someone help me here? Really thanks!

You need to declare the parameters as references, because otherwise you will be passing a copy instead of the original object, any change wont be reflected, until you receive references:

bool exploration(SpaceShip& sps){ ... }
bool select(SpaceShip& sps){ ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM