【发布时间】: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 你应该把它作为答案发布:)