[英]Initialization Lists - Can I initialize members with other members of the same class?
[英]How can I have a local variable that persists over time but is not shared among all members of the same class?
我正在虚幻引擎中编程 c++。 我有一些使用变量的函数,这些变量的值我需要及时持续,并且只在 function 中使用。 问题是,如果我将它们声明为 static 局部变量,当我有相同 class 的多个成员时,它们都共享相同的值,并且我希望每个 class 在一段时间内都有自己的局部变量实例。 我怎样才能做到这一点?
如果您真的想要这种级别的封装,您可以为每个成员变量创建一个单独的class
,并将对该变量进行操作的函数放在该 class 中。 然后,您可以从任意数量的这些单独的类中继承,以构建具有多个变量的 class。
例子:
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) {}
};
用法:
#include <iostream>
int main() {
foo f{1, 2};
std::cout << f.function_using_x() << f.function_using_y() << '\n'; // 12
}
你需要2个变量。 一个用于计数器(声明本地但螺母静态)并在一个实例中更改,另一个 static 用于跟随第一个变量;
但请注意,每次您需要 static 时,您都应该更新它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.