简体   繁体   English

管理嵌套类

[英]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? 现在如何访问BusStop对象中的方法? Should I add a "get_busStops()" method to the PIS class which would return a pointer to this vector? 我是否应该在PIS类中添加“ get_busStops()”方法,该方法将返回指向此向量的指针? Or maybe the vector busStops should be public? 还是矢量busStops应该是公共的? 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. 我能想到的最后一个解决方案是只返回一个存储在busStops向量中的BusStop对象的方法,该对象将其索引作为参数。

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. 我认为您应该将std::vector<BusStop> busStops私有,并在您的PIS类中实现方法,该方法将覆盖使用私有对象所需的所有操作,而不仅仅是返回指向整个向量甚至单个对象的指针。

To access methods in BusStop and below you can implement mirror methods in PIS class: 要访问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 };

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. 如果您仍然希望将指针返回给私有成员,那么将它们保持私有是没有意义的,而应该将它们设为公共-您将获得相同的写/读控制级别,但是将所有数据都保存在一个位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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