在单个指针数组中调用不同派生类的虚方法

时间:2015-04-25 05:55:39

标签: c++ arrays polymorphism components game-engine

好的,所以我试图为我的游戏引擎创建一个组件/实体系统,我有一个基础class component,它有虚拟方法update(),然后所有不同类型的组件都是派生自那个单一的基类。我将指向这些组件的指针存储在一个数组中,然后遍历调用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

从我在网上看到的,这样的接缝应该是可能的,因为数组只是拿着指针而不是对象本身,所以它们应该被切成基类。如果我对这个假设确实是错的,那会是什么解决方案?

2 个答案:

答案 0 :(得分:0)

//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();
}

答案 1 :(得分:0)

#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;
}

我在这里创建了一个链接demo code here。你可以用这个验证你的代码,并告诉你是否做了不同的事情?因为根据你所尝试的描述,你不应该看到不正确的行为,我也没有。