![](/img/trans.png)
[英]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.