如何通过调用基类的相同方法来调用继承类的方法?

时间:2012-08-16 12:42:01

标签: c++ oop

就像在XNA中的游戏引擎中一样,一次又一次地自动调用更新函数。我想知道如何用c ++实现这一点。

例如:

class base
{
void Update();
};

class child1: public base
{
void Update();
}

class child2: public base
{
void Update();
}

void main()
{
base *obBase = new base();
obBase->Update(); /*This should call Update of Child1 and Child2 classes how can I do  this*/
}

3 个答案:

答案 0 :(得分:4)

只需将其设为虚拟:

class base
{
    virtual void Update();
};

这将提供多态行为

我猜你了:

base *obBase = new child1(); //or new child2();

答案 1 :(得分:1)

您无法访问基类的派生类的所有实例。

您需要做的是拥有某种容器,它将存储Child1Child2类型的所有对象,然后在您决定时,遍历此容器并调用{ {1}}。

类似的东西:

Update

为了能够做到这一点,你需要使SomeContainer< base* > myObjects; // fill myObjects like: // myObjects.insert( new ChildX(...) ); // ... // iterate through myObjects and call Update 成为虚拟功能。

为了防止(潜在的)内存泄漏,请使用智能指针,而不是Update

答案 2 :(得分:0)

我猜你正在尝试使用多态,如下所示:

Base* obj1 = new Child1();
Base* obj2 = new Child2();

BaseManager* manager = new BaseManager(); //A class with a data struct that contains instances of Base, something like: list<Base*> m_objects;
manager->add(obj1); //Add obj1 to the list "m_objects"
manager->add(obj2); //Add obj2 to the list "m_objects"

manager->updateAll(); //Executes update of each instance in the list.
相关问题