【发布时间】: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