【发布时间】:2021-08-14 00:27:09
【问题描述】:
我有一个 Vheicle 类,它是子类 Bus、Helicopter、Train。 有没有办法将所有 Bus、Helicopter、Train 对象存储在一个数组中? 我在互联网上查看并没有找到任何可行的解决方案。
这是我的代码:
类声明:
class Vehicle {
private:
string vehicleID;
string man;
public:
Vehicle(string, string);
Vehicle();
virtual ~Vehicle();
};
class Bus: public Vehicle
{
public:
int currentMileage;
Bus(string, string, int);
Bus();
virtual ~Bus();
};
class Train: public Vehicle
{
public:
char motorType;
Train(string, string, char);
Train();
virtual~Train();
};
Vehicle::Vehicle(string id, string m) {
vehicleID = id;
man = m;
}
Bus::Bus(string id, string m, int curMile): Vehicle{id,m}{
currentMileage = curMile;
}
Train::Train(string id, string m, char mType):Vehicle(id,m){
motorType = mType;
}
我需要这个工作:
//method not related to this question
vehicleData bus = getBus(s1);
Vehicle* arrVehicle[2];
arrVehicle[0] = new Bus(bus.vehicleID, bus.man, bus.curMileage);
printf("%i\n", arrVehicle[0]->currentMileage);
printf("%c\n", arrVehicle[0]->man);
这是我遇到的错误
‘class Vehicle’ has no member named ‘currentMileage’
我在互联网上尝试了一些东西,但没有任何效果...错误类似于上述内容。
非常感谢您的回答。
【问题讨论】:
-
你错过了一个重要的点:每个
Bus都是Vehicle,但不是每个Vehicle都是Bus,因此并非每辆车都有一个成员currentMileage。currentMileage是否应该成为Vehicle的一部分? -
为了打印数组中的特定数据成员,您需要强制转换为适当的对象,然后访问细节。
-
你的问题标题会让读者感到困惑。你的问题本质上是关于对象层次结构的,但标题是关于数组的。
-
@churill 不,它不应该是
Vehicle的一部分,它不知道它叫什么,我只需要Bus对象及其在数组中的所有属性和@987654333 @ 对象,它的所有属性都在同一个数组中。所以我什么都不会错过。似乎每个Bus只是一个车辆,每个Train只是一个Vehicle而不是Train或Bus添加到数组后。这是一个问题,如何将同一父级的不同子级存储在一个数组中。 -
@SergeyA 这太奇怪了。标题讨论了数组中的同父对象。问题是关于数组中的子对象。
标签: c++ arrays oop inheritance