簡體   English   中英

管理嵌套類

[英]Managing nested classes

這是一個嵌套類的簡單示例,我認為在邏輯上是正確的:

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

我不確定該如何實現該接口。 這里的主要問題是訪問私有對象。 在下面,您可以看到我在說什么:

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

現在如何訪問BusStop對象中的方法? 我是否應該在PIS類中添加“ get_busStops()”方法,該方法將返回指向此向量的指針? 還是矢量busStops應該是公共的? 我能想到的最后一個解決方案是只返回一個存儲在busStops向量中的BusStop對象的方法,該對象將其索引作為參數。

我認為您應該將std::vector<BusStop> busStops私有,並在您的PIS類中實現方法,該方法將覆蓋使用私有對象所需的所有操作,而不僅僅是返回指向整個向量甚至單個對象的指針。

要訪問BusStop及以下版本中的方法,可以在PIS類中實現鏡像方法:

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 };

對每種方法執行此操作可能會令人沮喪,但是一旦實現,您的代碼將更容易為您和其他程序員使用和閱讀。

如果您仍然希望將指針返回給私有成員,那么將它們保持私有是沒有意義的,而應該將它們設為公共-您將獲得相同的寫/讀控制級別,但是將所有數據都保存在一個位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM