【问题标题】:Managing nested classes管理嵌套类
【发布时间】:2015-01-07 08:13:55
【问题描述】:

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

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 向量中,并将其索引作为参数。

【问题讨论】:

  • 我宁愿从getBusStops() 返回一个常量引用和/或引用,而不是一个指针。不管我会addBusStop(BusStop stop) 使用移动复制交换语义。在你知道它是什么之前,随意添加一个停止是没有意义的。但是,我看不到这个问题的“单一答案”解决方案,因为实施意见似乎很普遍。

标签: c++ class class-design


【解决方案1】:

我认为您应该离开 std::vector&lt;BusStop&gt; busStopsprivate 并在您的 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 };

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

如果您仍然希望将指针返回给您的私有成员,那么将它们保持私有是没有意义的,您应该将它们设为公开 - 您将实现相同的写入/读取控制级别,但您会将所有数据保存在一处。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2021-02-15
    • 2020-12-03
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多