Lar*_*ert 0 c++ oop inheritance class
我正在定义一个类GameState和一个MainMenuGameState类.前者是一个抽象类,后者是继承它.但不知何故,我无法覆盖其属性.
#ifndef _GAME_STATE_H_
#define _GAME_STATE_H_
#include <SDL2/SDL.h>
class GameState {
public:
virtual void loop(Uint32 deltaTime) = 0;
virtual void render() = 0;
virtual void event(SDL_Event * event) = 0;
bool stopRenderPropagation = false;
bool stopLoopPropagation = false;
};
#endif
Run Code Online (Sandbox Code Playgroud)
#ifndef _MAIN_MENU_GAME_STATE_H_
#define _MAIN_MENU_GAME_STATE_H_
#include "../Game.h"
class MainMenuGameState : public GameState {
public:
MainMenuGameState(Game * pGame);
void loop(Uint32 deltaTime);
void render();
void event(SDL_Event * event);
bool stopRenderPropagation = true;
bool stopLoopPropagation = true;
private:
Game * game;
int xOffset = 0;
int yOffset = 0;
};
#endif
Run Code Online (Sandbox Code Playgroud)
因此,在对MainMenuGameState对象进行实例化之后,我期望stopRenderPropagation并stopLoopPropagation成为true,但它们是false.
由于某种原因,我也没有运气在构造函数中覆盖它们.
MainMenuGameState::MainMenuGameState(Game * pGame) {
game = pGame;
xOffset = rand() % 20;
yOffset = rand() % 20;
stopRenderPropagation = true;
stopLoopPropagation = true;
}
Run Code Online (Sandbox Code Playgroud)
在那之后,他们仍然是真的.我不知道天气这是我的构造函数的问题,还是我误解了c ++中的多态性.
MainMenuGameState的实例存储在一个vector<GameState *>,这可能是问题吗?我正在访问这样的属性:
if(gameStates.begin() != gameStates.end()) {
std::vector<GameState *>::iterator it = gameStates.end();
do {
--it;
} while(it != gameStates.begin() && (*it)->stopLoopPropagation == false);
while(it != gameStates.end()) {
(*it)->loop(deltaTime);
++it;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助!
您的派生类声明了另一对成员在基类中具有相同名称的成员,因此"隐藏"了基类.
你应该接受构造函数中那些成员的初始值,或者如果它们是永远不会改变的类的固定属性,你应该使它们成为成员函数,就像在
class GameState {
public:
...
virtual bool stopRenderPropagation() { return false; }
virtual bool stopLoopPropagation() { return false; }
};
class MainMenuGameState : public GameState {
public:
...
bool stopRenderPropagation() { return true; }
bool stopLoopPropagation() { return true; }
...
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |