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&)':
错误:“。”之前的预期主表达式令牌”

最佳答案

尝试访问Leg.distance时,显然是您的错误。如果distance是Leg的静态成员,则需要通过Leg :: distance访问它。但是,正如您说的那样,您想创建一个单腿路线,而距离似乎是一个成员变量,实际上您需要在函数定义中指定参数名称:

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

关于c++ - 如何初始化指向对象的动态指针数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32920006/

10-10 21:24