gpt4 book ai didi

c++ - 类成员是一个类型未知的派生对象

转载 作者:行者123 更新时间:2023-11-30 03:44:34 26 4
gpt4 key购买 nike

我是 C++ 的新手,我正在创建一个假设的“飞行管理”应用程序作为学习经验并测试各种新技能。简单地说,我有一个 FlightPlan 类,其中包含一个私有(private)成员指针,指向一个类型为 Aircraft 的对象(好吧,现在)。

派生自 Aircraft 的对象在创建 FlightPlan 时已经存在,我希望能够分配派生的 AircraftFlightPlan 构建之后,而不只是在构建期间,对象指针指向 FlightPlan(将在计划中执行飞行的 a/c)。(使用诸如

flight-plan-obj.AssignAircaft(cargo-aircraft-obj-pointer);

我的问题是 AircraftCargoAircraftPassengerAircraft 派生的抽象类,因此不知道是什么“类型” aircaft 将在其 build 期间分配给飞行计划。我的代码如下。 (为简洁起见,省略了很多内容)

class FlightPlan {
private:
string departure;
string destination;

Aircraft* aircraft; // The a/c that will later be assigned to the flight
// Obviously this is currently wrong

public:
FlightPlan(string dep, string dest);
void AssignAircraft(Aircraft* ac);

// Other methods
}

Aircraft 抽象类:

class Aircraft {
protected:
Aircaft(string tailId, string acType); // ctor for the sub-classes

string tailId;
string acType;

public:
virtual string Overview() const =0; // pure virtual method
}

以及从 Aircraft 派生的对象示例:

class CargoAircraft : public Aircraft {
private:
int cargoCapacity;

public:
CargoAircraft(string tailId, string acType, int cargoCapcity);
string Overview() const override;

}
// ctor defined in the .cpp file as:
CargoAircraft::CargoAircraft(string tailId, string acType, int cargoCapacity)
: Aircraft(tailId,acType), cargoCapacity(cargoCapacity) {};

我想做的事情可行吗?我的理解是指针多态性允许我这样做:

Aircraft* aircraft; or Aircaft* aircraft = nullptr;

FlightPlan 中并且稍后会接受从 Aircraft 派生的类的对象指针?在编译时我收到:错误:‘Aircraft’ does not name a type

我的方法有什么根本性的错误吗?我是否需要放弃 Aircraft 的抽象性并将其更多地视为基类并为其提供公共(public)默认构造函数并使其方法只是虚拟的而不是纯虚拟的?

我会很乐意接受任何和所有的建议,我会很感激地接受任何其他关于我使用 C++ 的提示或技巧。谢谢。

最佳答案

你可以做两件事,

in FlightPlan and that would later accept an object pointer of a class derived from Aircraft? On compile I receive: error: ‘Aircraft’ does not name a type

标题必须包含在 Aircraft 类中,以便在 Flightplan 之前声明。或者你可以像这样使用前向声明

class Aircraft;

告诉 Aircraft 类型的编译器它存在并且可以声明您在 Flightplan 类中使用的指针。

您的问题仅与 Aircraft 类型的存在有关。使用前向声明或保证在声明飞行计划之前声明该类。

附言不要忘记 virtual destructor在飞机课上

关于c++ - 类成员是一个类型未知的派生对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35385512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com