【问题标题】:Passing a variable through parameters and modifying it later in the class通过参数传递变量并稍后在类中对其进行修改
【发布时间】:2020-11-04 20:57:57
【问题描述】:

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

例如:

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

【问题讨论】:

  • 为什么不使用成员变量?
  • 您可以存储对该成员的引用,或者创建一个std::function 并存储它
  • 因为不应该,所以需要分开。
  • 创建一个指针bool *mVar{};,然后在InitGlobalBool 中输入mVar = &var;,最后在Update 中执行类似*mVar = !(*mVar); 的操作。
  • @Ric 你应该把它作为答案发布:)

标签: c++ pointers reference


【解决方案1】:

我想你想做这样的事情:

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

【讨论】:

    猜你喜欢
    • 2019-05-18
    • 2017-11-30
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    相关资源
    最近更新 更多