【发布时间】: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->GetStartingPosition() 不起作用。基本上,当创建Car(new Car)的新实例时,我希望这辆车获得起始位置= 5(来自car.cpp),但最终命令不起作用。
谁能给我一些关于如何解决这个问题的提示?我认为这应该不会太难,但是我花了几个小时试图弄清楚,但我无法解决!任何帮助将不胜感激。
【问题讨论】:
-
您多次使用短语“不起作用”,但未能解释如何它不起作用。
-
欢迎来到 stackoverflow.com。请花一些时间阅读the help pages,尤其是名为"What topics can I ask about here?" 和"What types of questions should I avoid asking?" 的部分。也请take the tour 和read about how to ask good questions。最后请学习如何创建Minimal, Complete, and Verifiable Example。
-
AddVehicleToALane(new Car(0));呢?您的代码将位置传递给构造函数并忽略它,因此您可以传递任何内容。不是答案,因为我无法理解您在这里想要实现的目标...... -
应该使用 fVehicles[int i]->GetStartingPosition() 工作吗?我试过运行它,但每次运行它都会崩溃,但我不知道为什么。
-
v并不指向Vehicle(或任何东西,真的),所以你不能使用该指针调用 any 函数。
标签: c++ class inheritance derived-class base-class