我正在定义类 GameState 和类 MainMenuGameState。前者是抽象类,后者是继承类。但不知何故,我无法覆盖它的属性。
游戏状态.h
#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
MainMenuGameState.h
#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
所以在实例化 MainMenuGameState 对象之后,我期望 stopRenderPropagation
和 stopLoopPropagation
成为true
, 但它们是 false
.
出于某种原因,我也没有运气在构造函数中覆盖它们。
MainMenuGameState::MainMenuGameState(Game * pGame) {
game = pGame;
xOffset = rand() % 20;
yOffset = rand() % 20;
stopRenderPropagation = true;
stopLoopPropagation = true;
}
在那之后,它们仍然是真的。我不知道这是我的构造函数的问题还是我误解了 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;
}
}
感谢您的帮助!
最佳答案
您的派生类正在声明另外一对成员,它们与基类中的成员同名,因此“隐藏”了基类成员。
您应该在构造函数中接受这些成员的初始值,或者如果它们是类的固定属性且永不更改,您应该让它们成为成员函数,而不是像在
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; }
...
};
关于c++ - 覆盖抽象类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18974811/