[英]How can I have a local variable that persists over time but is not shared among all members of the same class?
I am programming c++ in Unreal Engine.我正在虚幻引擎中编程 c++。 I have some functions that use variables whose value I need to last in time and that are only used within that function.
我有一些使用变量的函数,这些变量的值我需要及时持续,并且只在 function 中使用。 The problem is that if I declare them as static local variables, when I have several members of the same class they all share the same value, and I would like each class to have its own instance of a local variable that lasts over time.
问题是,如果我将它们声明为 static 局部变量,当我有相同 class 的多个成员时,它们都共享相同的值,并且我希望每个 class 在一段时间内都有自己的局部变量实例。 How can I achieve this?
我怎样才能做到这一点?
If you really want that level of encapsulation, you could make a separate class
for each of your member variables and put the function(s) that operate on that variable in that class.如果您真的想要这种级别的封装,您可以为每个成员变量创建一个单独的
class
,并将对该变量进行操作的函数放在该 class 中。 You can then inherit from any number of those separate classes to build a class that has several variables.然后,您可以从任意数量的这些单独的类中继承,以构建具有多个变量的 class。
Example:例子:
struct func_x {
func_x(int X) : x{X} {}
int function_using_x() {
return x;
}
private:
int x; // only one member variable
};
struct func_y {
func_y(int Y) : y{Y} {}
int function_using_y() {
return y;
}
private:
int y; // only one member variable
};
struct foo : func_x, func_y { // inherit from both
foo(int x, int y) : func_x(x), func_y(y) {}
};
Usage:用法:
#include <iostream>
int main() {
foo f{1, 2};
std::cout << f.function_using_x() << f.function_using_y() << '\n'; // 12
}
you need 2 variables for that.你需要2个变量。 one for counter (declare local but nut static) and change in one instance and another static for following the first variable;
一个用于计数器(声明本地但螺母静态)并在一个实例中更改,另一个 static 用于跟随第一个变量;
but notice every time you need that static you should update it但请注意,每次您需要 static 时,您都应该更新它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.