我的项目中有一些带有静态属性的类。我怎样才能创建一个静态方法来填充这些静态属性从中读取数据的容器。如何在任何其他静态方法之前先运行一个静态方法。如何首先加载哪些类静态属性
答案 0 :(得分:0)
执行此操作的典型方法是将静态对象包装在getter函数中,以便在首次使用之前不会创建它。
这样,顺序取决于程序的设计。
该方案的一个例子如下:
class MyClass {
public:
static
MyContainer& GetTheContainer() {
static MyContainer* fgCon = new MyContainer; // happens at first demand
return *fgCon; // happens whenever MyClass::GetTheContainer() is called
}
static
SomeObj& GetFromContainerAt(const int i) {
MyContainer& c = GetTheContainer();
return c.At(i);
}
};
其余取决于程序的设计。您可以让其他类填充容器 - 只要他们使用GetTheContainer
,您就可以确保首先创建容器。或者你可以通过检查容器是否为空来填充容器(如果你确定它在创建时只会是空的),或者使用标志系统:
MyContainer& GetTheContainer() {
static MyContainer* fgCon = new MyContainer; // happens at first demand
static bool isNew = true; // only true the first time
if (isNew) {
// fill the container
isNew = false;
}
return *fgCon; // happens whenever MyClass::GetTheContainer() is called
}
例如,您可以在C++ Faq了解有关此方案的更多信息。