我正在用C++制作一个游戏,并且我的派生类遇到了问题.我有一个名为GameScreen的基类,它有一个没有语句的vitrual void draw()函数.我还有一个名为MenuScreen的派生类,它还有一个虚拟的void draw()函数和一个名为TestMenu的MenuScreen派生类,它也有一个void draw()函数.在我的程序中,我有一个GameScreens列表,我有一个GameScreen迭代器通过调用每个GameScreens draw()函数.
问题是我在GameScreen列表上放置了一个TestMenu对象.而不是迭代器调用TestMenu的draw()函数,而是调用GameScreen类的draw()函数.有谁知道如何调用TestMenu的draw()函数而不是GameScreen中的函数.
这是功能:
// Tell each screen to draw itself. //gsElement is a GameScreen iterator //gsScreens is a list of type GameScreen void Draw() { for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++) { /*if (gsElement->ssState == Hidden) continue;*/ gsElement->Draw(); } }
这是我的课程的副本:
class GameScreen { public: string strName; bool bIsPopup; bool bOtherScreenHasFocus; ScreenState ssState; //ScreenManager smScreenManager; GameScreen(string strName){ this->strName = strName; } //Determine if the screen should be drawn or not bool IsActive(){ return !bOtherScreenHasFocus && (ssState == Active); } //------------------------------------ //Load graphics content for the screen //------------------------------------ virtual void LoadContent(){ } //------------------------------------ //Unload content for the screen //------------------------------------ virtual void UnloadContent(){ } //------------------------------------------------------------------------- //Update changes whether the screen should be updated or not and sets //whether the screen should be drawn or not. // //Input: // bOtherScreenHasFocus - is used set whether the screen should update // bCoveredByOtherScreen - is used to set whether the screen is drawn or not //------------------------------------------------------------------------- virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ this->bOtherScreenHasFocus = bOtherScreenHasFocus; //if the screen is covered by another than change the screen state to hidden //else set the screen state to active if(bCoveredByOtherScreen){ ssState = Hidden; } else{ ssState = Active; } } //----------------------------------------------------------- //Takes input from the mouse and calls appropriate actions //----------------------------------------------------------- virtual void HandleInput(){ } //---------------------- //Draw content on screen //---------------------- virtual void Draw(){ } //-------------------------------------- //Deletes screen from the screen manager //-------------------------------------- void ExitScreen(){ //smScreenManager.RemoveScreen(*this); } }; class MenuScreen: public GameScreen{ public: vector
Curt Hagenlo.. 9
如果gsScreens是一个对象列表而不是一个指针列表(如代码所示),那么你就不会存储你认为存储在其中的内容.
发生的事情是 - 您不是将TestMenu放入列表中,而是使用编译器生成的复制构造函数构建一个新的MenuScreen,并将此MenuScreen放入列表中.
C++通过指针是多态的,所以如果你没有指针,你将不会获得多态行为.
如果gsScreens是一个对象列表而不是一个指针列表(如代码所示),那么你就不会存储你认为存储在其中的内容.
发生的事情是 - 您不是将TestMenu放入列表中,而是使用编译器生成的复制构造函数构建一个新的MenuScreen,并将此MenuScreen放入列表中.
C++通过指针是多态的,所以如果你没有指针,你将不会获得多态行为.