2012-08-16 45 views
1

就像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*/ 
} 
+0

通過「這應該叫Child1和CHILD2班我怎麼能做到這一點的更新」,你的意思是,你需要調用'更新'類型爲'Child1'和'Child2'的所有對象? – 2012-08-16 12:44:09

回答

4

就讓它虛:

class base 
{ 
    virtual void Update(); 
}; 

這將提供多態行爲

而且我認爲你彪:

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

你可以不能訪問所有實例s的基類派生類。

你需要做的是有某種容器,將存儲Child1類型和Child2的所有對象,然後,當你決定,遍歷這個容器,並呼籲Update的。

喜歡的東西:

SomeContainer< base* > myObjects; 
// fill myObjects like: 
// myObjects.insert(new ChildX(...)); 
// ... 
// iterate through myObjects and call Update 

爲了能夠做到這一點,你需要做Update的虛函數。

爲防止(潛在)內存泄漏,請使用智能指針而不是base*

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.