c++ - 覆盖抽象类的属性

标签 c++ class oop inheritance

我正在定义类 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 对象之后,我期望 stopRenderPropagationstopLoopPropagation成为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/

相关文章:

c++ - xxx.h : fatal error C1083: Cannot open include file: 'yyyy.h' : No such file or directory

c++ - 比较两个指针数组,其中一个来自 .h,另一个来自 cin

c++ - 地址窗口扩展

php - 如何在php中模仿模板类

c# - 对实体使用泛型

javascript - JS 继承示例 : too much recursion

c++ - 关于对 typedef 的 undefined reference 的 g++ 错误

delphi - 类(class)助手有什么用处?

python - 通过 find_element_by_class_name 单击按钮不起作用 python selenium webdriver 不工作

c# - 列表类的类结构?