【问题标题】:Inheriting a method from a base class (vehicle) and value from a derived class (car) to implement in another derived class (lane) using C++从基类(车辆)继承方法并从派生类(汽车)继承值,以使用 C++ 在另一个派生类(车道)中实现
【发布时间】:2018-06-12 03:58:46
【问题描述】:

我有一个关于 C++ 继承的问题。 Vehicle 类具有 SetStartingPosition()GetStartingPosition() 函数。 Car 类继承了这些函数,并在 SetStartingPosition(5) 的构造函数中将起始位置设置为 5。

我想要的是,当使用AddVehicleToALane(Vehicle* vehicle) 函数将新车(new Car)添加到车道(在Lane 类中)时,此Car 的位置被分配值为 5。

Vehicle.h:

Class Vehicle{
public:
    Vehicle();
    Vehicle(double position);
    virtual ~Vehicle();
    void SetStartingPosition(double startingpos){
        fStartingPos = startingpos
    }

    double GetStartingPosition(){
        return fStartingPos;
    }

private:
    double fStartingPos;
}    

Car.h:

#include "vehicle.h"
Class Car: public Vehicle{
public:
    Car();
    Car(double position);
}

Car.cpp:

Car::Car(double position): Vehicle(position){
    SetStartingPosition(5);
}

车道.h:

#include "vehicle.h"
#include "car.h"
Class Lane{
public:
    void AddRandomVehicle();

    void AddVehicleToALane(Vehicle* vehicle){
     fVehicles.push_back(vehicle);
    }

private:
    std::vector<Vehicle*> fVehicles;
    Vehicle *v;
}

车道.cpp:

void Lane::AddRandomVehicle(){
    int i = 0;
    AddVehicleToALane(new Car(fVehicles[i]->GetStartingPosition()));
}

最后的命令v-&gt;GetStartingPosition() 不起作用。基本上,当创建Carnew Car)的新实例时,我希望这辆车获得起始位置= 5(来自car.cpp),但最终命令不起作用。

谁能给我一些关于如何解决这个问题的提示?我认为这应该不会太难,但是我花了几个小时试图弄清楚,但我无法解决!任何帮助将不胜感激。

【问题讨论】:

标签: c++ class inheritance derived-class base-class


【解决方案1】:

您的代码有很多问题。

Lane::v 永远不会被分配,所以当你v-&gt;GetStartingPosition() 时,你有未定义的行为。

Vehicle 没有接受double 的构造函数,因此Car::Car(double position): Vehicle(position) 是一个语法错误。

Car::Car(double position) 是私有的,因此您只能在 Car 方法中使用 new Car(...)

为什么 car 需要 double position 然后覆盖它?为什么不Car::Car() { SetStartingPosition(5); }

为什么你有一个Car根本Vehicle 构造后你没有任何区别,而且Vehicle 的方法都不是虚拟的(尤其是析构函数!)

【讨论】:

  • 另外,Car(double position) 是私有的,所以他根本无法创建 Car。
  • 这些是有用的提示。 @Caleth 你是说我的 SetStartingPosition(5) 函数可以放在 Car::Car() {} 构造函数中吗?
  • @dsp_user 你能解释一下我该如何解决这个问题吗?
  • 只需添加 public: Car();车(双);与结构不同,类的所有成员都是私有的,除非明确声明为公共(或受保护)
  • 请注意,您仍然需要为构造函数定义主体 (Vehicle(double position) {} * (在这种情况下,您定义了一个空主体 ( {} ),它没有有意义,因为您将参数传递给构造函数,因此最好使用 *Vehicle(double position) { fStartingPos = position; } 甚至 *Vehicle(double position) : fStartingPos(position) {} *
猜你喜欢
  • 1970-01-01
  • 2012-12-10
  • 2014-12-23
  • 2021-08-24
  • 2011-01-08
  • 1970-01-01
  • 2016-07-03
  • 2021-12-20
  • 2015-01-20
相关资源
最近更新 更多