通过参数传递变量并在稍后的类中对其进行修改

问题描述

如何将变量存储在类中,然后在程序流程中对其进行修改

例如:

bool bGlobalStatus = false;

class foo
{
public:

    foo(){}
    ~foo(){}

    void InitGlobalBool(bool &var)
    {

        // I can change the value here,but I want to store the variable and modify it later.
        // var = !var;
    }

    void Update()
    {
        // this will be called in program flow ...
        var = !var; // this variable should be in my case bGlobalStatus,depends which variable I put inside the InitGlobalBool function 
    }
};

int main()
{
   foo Foo;
   Foo.InitGlobalBool(bGlobalStatus); 
   return 0;
}

解决方法

我认为您想做这样的事情:

bool bGlobalStatus = false;

class foo
{
public:
    bool *mVar{};
    foo(){}
    ~foo(){}

    void InitGlobalBool(bool &var)
    {

        mVar = &var;
    }

    void Update()
    {
        *mVar = !(*mVar);
    }
};

int main()
{
   foo Foo;
   Foo.InitGlobalBool(bGlobalStatus); 
   return 0;
}