【问题标题】:How to initialize a dynamic array of pointers to an object?如何初始化指向对象的动态指针数组?
【发布时间】:2015-12-31 10:07:18
【问题描述】:
class Leg
{
public:
  Leg (const char* const s  ,  const char* const e  , const double d) : startCity (s), endCity (e), distance (d) {}
  friend void outputLeg( ostream&  , const Leg& ) ;

private:
  const char* const startCity  ;
  const char* const endCity  ;
  const double distance;
};


class Route
{
public:

/* Include two public constructors --

(1) one to create a simple route consisting of only one leg,
The first constructor's only parameter should be a const reference to a Leg object.*/

  Route ( const Leg& ) : arrayHolder( new const Leg* [1]  ), arraySize( 1 ), r_distance( Leg.distance )  {}


//(2) another to create a new route by adding a leg to the end of an existing route.

private:

  const Leg** const arrayHolder;//save a dynamically-sized array of Leg*s as const Leg** const.
  const int arraySize;//save the size of the Leg* array as a const int .
  const double r_distance;//store the distance of the Route as a const double, computed as the sum of the distances of its Legs.
};

我可以澄清一下我在第一个构造函数中所做的事情。如何正确保存传递的 Leg 对象的指针?

当前得到'在构造函数'Route::Route(const Leg&)'中: 错误:“。”之前的预期主表达式令牌'

【问题讨论】:

    标签: c++ arrays oop pointers


    【解决方案1】:

    您的错误显然是在尝试访问 Leg.distance 时。如果 distance 是 Leg 的静态成员,则需要通过 Leg::distance 访问它。但是你说要创建one-Leg路由,貌似distance是一个成员变量,实际上需要在函数定义中指定一个参数名:

    Route (const Leg& L) : arrayHolder( new const Leg* (&L)),
                           arraySize(1),
                           r_distance(L.distance) {}
    

    【讨论】:

    • 啊,我应该包括腿部课程,现在就这样做。问题是距离是私人成员。有没有办法在不公开的情况下访问它?
    • @Vic 不,除非你做以下三件事之一: - 将类 Route 声明为朋友, - 添加一个 getter 函数 getDistance(),或 - 公开距离。 getter 函数是推荐的方法,当然
    【解决方案2】:

    我在您的代码中看不到“距离”是什么,但是您在类定义 Leg 中使用它,因此它仅在距离是静态变量时才有效。您不是说要使用正在通过的腿的距离吗?像这样:

    Route ( const Leg& myLeg) : arrayHolder( new const Leg* [1]  ), arraySize( 1 ), r_distance( myLeg.distance )  {}
    

    至于您要存储的指针:您将它作为引用传递,那么为什么不将它也存储为引用呢?像这样的:

    class Route
    {
    public:
        Route ( const Leg& myLeg ): theLeg( myLeg ) {}
    private:
        const Leg& theLeg;
    };
    

    【讨论】:

    • 必须初始化引用。
    • 我在初始化列表中初始化了theLeg。你到底是什么意思?
    • 是的,你做到了。但现在它需要在每个构造函数中初始化。如果某个构造函数没有任何 Leg 怎么办?顺便说一句,腿应该是 OP 问题中的一个集合。
    猜你喜欢
    • 2014-03-14
    • 1970-01-01
    • 2013-06-30
    • 2016-08-16
    • 2010-10-11
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多