C ++ - 在创建游戏实体时,我应该使用“子类”还是结构?

时间:2017-03-07 20:24:47

标签: c++ game-engine

我正在学习如何为学校制作游戏。在这个游戏中,我有三种不同类型的船:驱逐舰,航母和快艇。我将声明一个entityType枚举:

enum EntityType {DESTROYER, CARRIER, SPEEDBOAT};

我必须有一个看起来像的实体类:

class Enitity 
{
private:
    float acceleration, turnRate, maxSpeed, minSpeed;
    std::string entityType;
public:
    Entity(EntityType type);
    ~Entity();
    //Rest of class
};


对于每种船型,它们具有不同的值。我对每种类型的船都有不同的值,我试图找出初始化每种类型船的最佳方法。我想到了三种方法。我也试图做到这一点,以便将来可以在此基础上建立更多的船型。


选项1:创建一个包含EntityData结构的文件,并为每种发货类型创建数据,如:

struct EntityData
{
    float acceleration, turnRate, maxSpeed, minSpeed;
    std::string entityType;
};

EntityData DestroyerData;
DestroyerData.acceleration = 5;
DestroyerData.turnRate = 2; 
DestroyerData.maxSpeed = 35;
DestroyerData.minSpeed = 0;
DestroyerData.entityType = "Destroyer";

EntityData CarrierData;
CarrierData.acceleration =2;
.....

然后在Entity类的构造函数中有一个switch语句,如果entityType是DESTROYER,则将类的数据设置为struct的数据。

Entity::Entity(EntityType type)
{
    EntityData data;
    switch (type)
    {
    case EntityType::DESTROYER:
        data = DestroyerData;
        break;
    case EntityType::CARRIER:
        break;
    default:
        break;
    }

    acceleration = data.acceleration;
    maxSpeed = data.maxSpeed;
    //Rest of variables
}


选项2:使用继承并使Entity类成为基类,并使每种船类都拥有自己的类。在它的类中只是在构造函数中初始化了这些值。

class Destroyer : public Entity 
{
public:
    Entity(EntityType type);
    ~Entity();
    //Rest of class
};

Destroyer::Destroyer()
    : acceleration(5),
      maxSpeed(35), 
      //Rest of variables
{
}


选项3:通过在Entity的构造函数中使用switch语句,而不使用数据结构或继承的类,使Entity类中的所有信息都基于实体类型设置?

Entity::Entity(EntityType type)
{
    switch (type)
    {
    case EntityType::DESTROYER:
        maxSpeed = 42;
        //TODO: Set the rest of the variables for the DESTROYER
        break;
    case EntityType::CARRIER:
        //TODO: Set the rest of the variables for the CARRIER
        maxSpeed = 55;
        break;
    default:
        break;
    }
}


哪种方法最好?为什么?



如果投票不足请解释投票原因,以便改进我的问题。

1 个答案:

答案 0 :(得分:1)

利用C ++ OOP的最佳方法是继承。这将允许您使用std :: vector< * genericShip> fleet,并将所有三种类型存储在其中。此外,例如,如果一个驱逐舰可以发射一个大炮,一个载体可以发射一架飞机,但是快艇不能,这种方法可以让你为每个飞机实现功能。另一个优点是,如果您需要单独调整特定船舶的值,这种方法将允许这样做,最后,您可以轻松添加新船。

相关问题