繁体   English   中英

C ++当我从另一个类的方法调用一个方法时,它可以工作,但不编辑第一个方法的类的变量

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

如标题所述,我在这里有此代码

#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;
}

当我从主对象调用ConsumeFuel(x)时,它会很好地编辑对象的燃料变量,而当我从MissionSelector类的探索方法(我在MissionSelector的select方法中调用,该方法在主对象中调用)中进行编辑时它返回true,但从不编辑燃料变量。

我省略了代码的其他部分,因为它只是其他细节,并没有真正帮助您找到此处的错误,主要是其他资源和其他任务。 而且stackoverflow一直告诉我没有足够的细节,因为它主要是代码,但实际上是这里的一切,仅此而已,我将添加以下几行以使其高兴。

有人可以帮我吗? 真的感谢!

您需要将参数声明为引用,因为否则您将传递副本而不是原始对象,任何更改都不会反映出来,直到您收到引用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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