【发布时间】:2015-07-03 21:19:39
【问题描述】:
好的,所以我正在尝试为我的游戏引擎制作一个组件/实体系统,并且我有一个基础 class component,它具有虚拟方法 update(),然后所有不同类型的组件都来自那个单一的基类。我将指向这些组件的指针存储在一个数组中,然后循环调用更新方法的数组。当我只有一种类型的派生类时,它会调用派生虚方法,但是一旦我添加了不同类型的派生类,它就会开始使用基本更新方法。这是和示例:
//Hold the pointers to the Components
Component** components;
//in the system constructor I initialize the array of components
void System::System()
{
components = new Component*[MAX_COMPONENTS]();
}
//Inputlistener is a derived component
InputListener* inputListener;
inputListener= new InputListener;
//Playercontroller is also derived component
PlayerController* playerController;
playerController = new PlayerController;
//Adds the pointer to the components array
system->add(inputListener);
system->add(playerController);
//loops over the array the update method is a virtual method
system->update(); //calls the base classes update method not the derived
从我在网上阅读的内容来看,这样的接缝应该是可能的,因为数组只是保存指针而不是对象本身,因此它们应该被分割到基类中。如果我对这个假设确实错了,那么解决方案是什么?
【问题讨论】:
-
你试过了吗?它奏效了吗?在旁注中,为什么不至少使用
vector<Component*>- 最好是一些智能指针结构。 -
很遗憾您没有显示任何重要的代码。无论如何,答案是你在一些你没有显示的代码中有一个错误。
-
看起来没有错。发布一个展示问题的最小且完整的示例。
标签: c++ arrays polymorphism components game-engine