2016-02-13 105 views
1

我对C++相对较新,我正在创建假设的“Flight Management”应用程序作为学习体验并测试各种新技能。简而言之,我有一个FlightPlan类,其中包含一个私有成员指针,指向Aircraft类型的对象(当然,现在)。从Aircraft衍生类成员是派生对象,其类型尚未知晓

对象是预先存在的在FlightPlan创建时,我希望能够分配一个Aircraft派生对象指针FlightPlan(所述的A/C,将执行该计划的飞行)在建造FlightPlan之后,而不仅仅是在施工期间。 (使用方法如

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

我的问题是Aircraft是一个抽象类,CargoAircraftPassengerAircraft从,因此它不知道什么“类型”的过程中它的aircaft将被分配到飞行计划派生。建设我的代码如下(很多人都忽略了为简洁起见)

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是抽象的,只是把它看作更多的基类,并给它一个公共的默认构造函数,并使它的方法只是虚拟的,而不是纯虚拟的?

任何和所有的建议都会得到大家的好评,我会非常感激地接受任何关于我使用C++的提示或提示。谢谢。

+0

查看转发声明。 –

回答

2

你可以做两件事情,

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

头必须包含与类飞机所以它飞行计划之前声明。或者你可以使用前置声明这样

class Aircraft; 

告诉它的存在和指针可以声明在类飞行计划使用类型飞机的编译器。

你的问题只是关于类型飞机的存在。使用前向声明或保证在声明Flightplan之前声明了类。

P.S.不要忘记在Aircaft中的virtual destructor

+0

感谢您记住这一点。 –

+0

您的建议很受欢迎,谢谢。 FlightPlan.h中已经有了Aircraft.h,但这并不适合我。前向声明的确如此,我也曾用它来解决其他一些问题。再次感谢。 – ajgio23

相关问题