简体   繁体   中英

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.

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. 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).

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. 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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM