管理嵌套类

时间:2015-01-07 08:13:56

标签: c++ class class-design

这是嵌套类的一个简单示例,我认为这在逻辑上是正确的:

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应该公开?我能想到的最后一个解决方案是一个只返回一个BusStop对象的方法,该对象存储在busStops向量中,它将索引作为参数。

1 个答案:

答案 0 :(得分:3)

我认为你应该将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 };

为每种方法执行此操作可能会令人沮丧,但是一旦您实现它,您和其他程序员的代码将更易于使用和阅读。

如果您仍希望向私人成员返回指针,那么将它们保密是没有意义的,您应该将它们公之于众 - 您将获得相同的写入/读取控制级别,但您将保留所有数据一个地方。

相关问题