继承类的矢量

时间:2014-04-14 12:46:43

标签: c++ inheritance vector

我一直在四处寻找解决方案,

我有一些从一个基类继承的类:

#ifndef navalVesselClass
#define navalVesselClass

#include <iostream>
#include <string>
class navalVessel
{

public:
    std::string Name_;
    std::string Type_;
    std::string OperatingCountry_;
    std::string Built_;
    std::string ServiceDate_;
    bool Active_;
    double Length_;
    double Displacement_;
    double Beam_;
    double Draft_;
    double Speed_;
    double Range_;


private:

};

#endif

然后,例如继承它的类:

#ifndef destroyerClass
#define destroyerClass

#include "surfaceCombatant.h"
#include <string>




class destroyer: public surfaceCombatant
{
public: 
    enum class ArmamentPrimary { ANTIAIR, MISSILE };
    enum class ArmamentSecondary { TORPEDOS, MISSILE, ANTIAIR, ANTIGROUND };        
    ArmamentPrimary primaryArmament;
    ArmamentSecondary secondaryArmament;
private:

};



#endif

现在,当我想在矢量中存储这些对象时,我正在创建一个矢量,如下所示

std::vector<navalVessel *> shipFleet

使用它,我可以将此向量中的两个,驱逐舰和其他船只存储为指针,但是一旦我再次尝试检索它们,它们当然是“navalVessel”类型,我无法访问任何派生类变量?例如主要武器,我只能访问基类属性。

感谢。

2 个答案:

答案 0 :(得分:2)

您的设计存在缺陷,如果不启用RTTI并使用dynamic_cast,您将无法执行此操作。 但这没用,因为你的设计会变坏或变得更糟。

我建议阅读一些OOP基础知识,因为你没有完全理解基类和多态的含义。

基类的想法是提供一组通用的方法,这些方法根据具体类型的实现产生不同的值。

在你的场景中,你的基类应该提供一个成员来获取可能的武器列表,每个具体的实现都将返回他们的武器集。没有武器的船只将返回一个空列表等。

但是又来了。你在理解C ++中的抽象类时有很深的缺陷。绝对有必要在基类中至少提供一个虚拟析构函数。

答案 1 :(得分:0)

将navalVessel *转换为实际类型的任何派生类的指针。使用dynamic_cast。