【问题标题】:Calling virtual methods of different derived classes in a single array of pointers在单个指针数组中调用不同派生类的虚方法
【发布时间】: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


【解决方案1】:
//Hold the pointers to the Components
std::vector<Component*> components;

//Inputlistener is a derived component   
InputListener* inputListener;
inputListener= new InputListener;

//Playercontroller is also derived component
PlayerController* playerController;
playerController = new PlayerController;

components.push_back(inputListener);
components.push_back(playerController);

for( size_t i = 0; i < components.size(); ++i ){
  Component* cmp = components.at(i);
  if( cmp ) cmp->update();
}

【讨论】:

  • 这是否真的回答了 OP 的任何问题(我同意向量 tho')
  • @MatsPetersson 其实我只是想通过显示一些代码来给出提示。
【解决方案2】:
#include <iostream>

using namespace std;

class Base {
    public:
    virtual void update (){
        cout << "Base" << endl;
    }
};

class Derived1 : public Base {
    public:
    void update () override{
        cout << "Dervied1" << endl;
    }
};

class Derived2 : public Base {
    public:
    void update () override{
        cout << "Dervied2" << endl;
    }
};

int main()
{
   Base* sample[3];
   sample[0] = new Base();
   sample[1] = new Derived1();
   sample[2] = new Derived2();

   for(int i=0; i < 3; ++i){
       sample[i]->update();
   }
   return 0;
}

我在这里创建了一个链接 http://codepad.org/IfnBdYIk 。你能用这个验证你的代码并判断你是否在做不同的事情吗?因为从你尝试过的描述来看,你不应该看到错误的行为,我也没有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 2016-07-03
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 2020-02-11
    相关资源
    最近更新 更多