[英]Sharing static data members between different classes that can create instances of eachother
I have written a class (AbcdBase) which holds several static objects, these include maps and a few static objects that act as "helper tools" such as plotting helper functions, objects which store constants for making tables and so on.我编写了一个类(AbcdBase),它包含几个静态对象,其中包括地图和一些充当“辅助工具”的静态对象,例如绘图辅助函数、存储用于制作表格的常量的对象等。
Separately I have other classes (DataSample and DoABCD) that need access to those static members, the twist is that DoABCD creates several instances of DataSample.另外,我还有其他需要访问这些静态成员的类(DataSample 和 DoABCD),不同之处在于 DoABCD 创建了几个 DataSample 实例。 What would be the correct way of coding this?
对此进行编码的正确方法是什么? Having both DataSample and DoABCD be derived classes of AbcdBase doesn't seem like the correct way (and I get Seg violations when I do that).
让 DataSample 和 DoABCD 都是 AbcdBase 的派生类似乎不是正确的方法(当我这样做时我会违反 Seg)。
class AbcdBase {
private:
int init();
int status;
public:
static SampleAggregator* SampleAggregatorInst;
static PlotHelper* PlotHelperInst;
static DataSampleConst* DataSetMap;
static DataSampleConst::SampleDict* ListOfSamples;
static std::vector<std::string> ListOfPlots;
static std::vector<std::string> ListOfRegions;
static Logger* LoggerInst;
AbcdBase();
virtual ~AbcdBase();
typedef enum {
A = 1, B = 2, C = 3, D = 4
} RegionEnum;
typedef enum {
MET = 1, ETCONE20 = 2
} DimensionEnum;
ClassDef(AbcdBase, 1)
};
Is a singleton the correct way of solving this issue?单身人士是解决这个问题的正确方法吗? so that whenever DataSample or DoABCD need access to a member of AbcdBase they instance() function gets called which returns a pointer to a private instance of AbcdBase.
这样每当 DataSample 或 DoABCD 需要访问 AbcdBase 的成员时,就会调用 instance() 函数,该函数返回指向 AbcdBase 私有实例的指针。 I feel like this would clutter the code a LOT.
我觉得这会使代码混乱很多。
Thanks谢谢
Separately I have other classes (DataSample and DoABCD) that need access to those static members
另外,我还有其他需要访问这些静态成员的类(DataSample 和 DoABCD)
Merely declare those static member public, as you have done, and then reference them in any other code (including the code in DataSample or DoABCD:只需像您所做的那样将这些静态成员声明为 public,然后在任何其他代码中引用它们(包括 DataSample 或 DoABCD 中的代码:
class DataSample {
...
int GetFragle(void) {
return AbcdBase::PlotHelperInst->m_fragle;
}
...
};
No need to do anything.无需做任何事情。
They're already public, you can use AbcdBase::PlotHelperInst from ANYWHERE.它们已经公开,您可以从任何地方使用 AbcdBase::PlotHelperInst。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.