【发布时间】:2021-11-13 18:17:03
【问题描述】:
我对 C++ 相当陌生,并且正在从事一个个人项目。我想在 C++ 中创建一个 vector<Entity*> entitities,其中每个 Entity 对象都是唯一的。我在标题Entity.h 中有一个要创建的类。现在 Entity 有两个成员变量:
-
Rectangle rect- 一个Rectangle类型的对象,它有四个浮点变量作为成员变量(x1、y1、x2、y2),它们是矩形两个对角的坐标 -
vector<Component*>- 基类类型Component的许多不同组件以及一些派生类。Class Component的代码如下所示:
/*************************** BASE CLASS **************************/
class Component
{
public:
virtual ~Component() = default;
virtual Component* Clone() = 0;
};
/*************************** DERIVED CLASS 1 **************************/
class BasicComponent: public Component
{
private:
int B= 0;
public:
BasicComponent* Clone() override {
return new BasicComponent(B);
}
BasicComponent(const int& mB) :B(mB){}
BasicComponent() :B(0) {}
};
/*************************** DERIVED CLASS 2 **************************/
class AdvancedComponent: public Component
{
private:
float A = 0.f;
int iA = 0;
public:
AdvancedComponent* Clone() override {
return new AdvancedComponent(A, iA);
}
AdvancedComponent(const float& mA, const int& miA) :A(mA),iA(miA) {}
AdvancedComponent() :A(0.f),iA(0) {}
};
由于我希望实体向量中的每个Entity 都是唯一的,即拥有自己的矩形和组件,我应该如何创建类?
我的问题是,class Entity 应该是什么样子?我应该为这个类创建单独的 CopyConstructor、Assignment Constructor 和 Destructor 吗?另外,如果我想实现将一个实体复制到另一个实体(深度复制),是否有必要拥有全部 3 个(复制、赋值和析构函数)?
【问题讨论】:
-
你给
Entity的成员了,对吧?是什么阻止您编写课程? -
为什么
vector<Entity*>相关?只是说每个Entity都必须有自己的Rectangle和Components 的副本,这还不够吗? -
@RahulPillai:C# 有指针;它只是没有语法。
-
@RahulPillai “使用
vector<Entity*>而不是vector<Entity>有错吗?” -- 这不是我想要的。您在询问您的代码;我说的是你的问题。更简单的问题分心更少,因此更有可能得到回答而不会迷失方向。如果您从您的问题中删除所有提及向量并仅声明每个Entity必须有自己的Rectangle和Components,会丢失什么? (强调向量而不是要求,看起来好像不在向量中的对象必须共享矩形和组件。) -
使用动态分配的原因有很多,但如果你真的想要动态生命周期,那么原则上你不需要它。但是,如果您想要运行时多态性(正如您的组件子类所示),没有间接性就很难做到。
标签: c++ c++11 entity-component-system