我正在学习如何为学校制作游戏。在这个游戏中,我有三种不同类型的船只:驱逐舰,航母和快艇。我会申报的EntityType枚举:C++ - 当创建游戏实体时,我应该使用“子类”还是结构?
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;
.....
则该实体类的构造函数中有一个switch语句,如果entityType是DESTROYER将类的数据设置为结构的数据。
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:使用继承,使实体类的基类,并让每个船型有它自己的类。在它的类中,只有在构造函数中初始化了这些值。
class Destroyer : public Entity
{
public:
Entity(EntityType type);
~Entity();
//Rest of class
};
Destroyer::Destroyer()
: acceleration(5),
maxSpeed(35),
//Rest of variables
{
}
方案3:通过提供实体的构造函数使用switch语句,而不是使用数据结构或继承类基于关闭实体类型的实体类中设置的所有的信息?
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;
}
}
哪种方法是最好的,为什么?
如果反对投票 -请解释一下你为什么反对投票,所以我可以提高我的问题。
您会如何期待对性能产生影响? –
也许是由工厂函数构造和初始化的通用“Ship”类,它根据类型(来自预定义的“船舶类型”的表或地图,不使用switch语句或类似语言)? –
如果所有的船只都有相同的参数组,并且只有数值不同,继承和为每个类型定义一个自己的结构都是过度的。只需使用同一类的不同对象。 –