如何初始化指向对象的动态指针数组?

时间:2015-10-03 07:21:56

标签: c++ arrays oop pointers

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&)': 错误:'。'之前的预期primary-expression令牌'

2 个答案:

答案 0 :(得分:0)

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

...
function($scope, $timeout) {
        var marker, map, infoWindow;
        $scope.$on('mapInitialized', function(evt, evtMap) {
            map = evtMap;
            marker = map.markers[0];
            // get the info-window by it's id foo
            infoWindow = map.infoWindows['foo'];
        });
       ...

答案 1 :(得分:-1)

我无法在您的代码中看到距离'事情是,但是你在类定义Leg上使用它,所以只有当distance是一个静态变量时它才有效。你不是故意使用正在通过的腿的距离吗?像这样:

URL website = new URL("http://server1/file_location");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("file_name");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

至于你试图存储的指针:你将它作为参考传递,那么为什么不将它作为参考存储呢?像这样:

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