简体   繁体   中英

Managing nested classes

Here's a simple example of nested classes, which in my opinion is logically correct:

class PIS{ // passenger information system
    public:
        class BusStop;
        void add_busStop();
        //... other methods
    private:
        std::vector<BusStop> busStops; //There are many bus stops
};

class PIS::BusStop{
    public:
        struct BusInfo;
        std::string get_stopName();
        //... other methodes
    private:
        std::vector<BusInfo> informationBoard;
};

struct PIS::BusStop::BusInfo{
    std::string mfrom;
    std::string mto;
    //... etc.
};

I'm not sure how I should implement the interface for that. The main problem here is accessing the private objects. Below you can see what I'm talking about:

PIS oPIS; //PIS object;
oPIS.add_busStop(); //New BusStop object is pushed to the vector busStops

Now how do I access the methods in the BusStop object? Should I add a "get_busStops()" method to the PIS class which would return a pointer to this vector? Or maybe the vector busStops should be public? Last solution that I can think of is a method that would return only one BusStop object, stored in the busStops vector, which would take it's index as an argument.

I think you should leave std::vector<BusStop> busStops private and in your PIS class implement methods that will cover all operations that will be needed to work with your private objects instead of just returning pointer to the entire vector or even a single object.

To access methods in BusStop and below you can implement mirror methods in PIS class:

class PIS{ // passenger information system
public:
    class BusStop;
            std::string get_StopName(int iBusStopIndex){return busStops[iBusStopIndex].get_StopName();};
            void add_busStop();
            //... other methods
        private:
            std::vector<BusStop> busStops; //There are many bus stops };

It may be frustrating to do this for every method, but your code will be simplier to use and read for you and other programists once you implement it.

If you still wish to return pointers to you private members then there is no point in keeping them private and you should make them public instead - you will achieve the same write/read control level, but you will keep all your data in one place.

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