错误:"分配抽象类类型的对象"尽管所有虚拟功能都已实施

时间:2016-10-13 14:28:16

标签: c++ xcode sdl

我收到错误"分配抽象类类型的对象' MainGame"即使已经实现了所有虚拟功能。以下是相关的代码段:

main.cpp

#include "Gamestate_MainGame.h"

int main() {
    Game game;
    if (game.init(new MainGame))
        game.loop();
    return 0;
}

Gamestate.h

#ifndef Gamestate_h
#define Gamestate_h
#include <SDL2/SDL.h>
#include "Game.h"

class GameState {
public:
    virtual bool init(Graphics* graphics, Game* game) = 0;
    virtual void quit() = 0;

    virtual void handleEvents(SDL_Event* e) = 0;
    virtual void logic() = 0;
    virtual void render() = 0;

protected:
    Game* game = NULL;
    Graphics* graphics = NULL;
};
#endif

Gamestate_MainGame.h

#ifndef Gamestate_MainGame_h
#define Gamestate_MainGame_h
#include <vector>
#include <SDL2_mixer/SDL_mixer.h>
#include "Gamestate.h"
#include "Graphics.h"
#include "Tile.h"

class MainGame : public GameState {
    // Gamestate Functions
    bool init(Graphics* graphics, Game* game);
    void quit();

    void handleEvents(SDL_Event& e);
    void logic();
    void render();

    // MainGame functions - make private?
    void makeTiles();
    void loadPositions(const int & n);
    void scrambleTiles(std::vector<Tile> t);
    void restart();

    bool isSolved();
    bool isNeighbor(const Tile& a, const Tile& b);
    int  getClickedTile(const int& x, const int& y);

private:
    Game* game = NULL;
    Graphics* graphics = NULL;

    int  clickedTile { -1 };
    int  clicks      { 0 };
    bool gameExit    { false };
    bool gameWin     { true  };
    bool catMode     { true };

    std::vector<Tile> tiles;
    std::vector<SDL_Rect> positions;

    Mix_Chunk* click = NULL;

};
#endif

Game.h

#ifndef Game_h
#define Game_h
#include <vector>
#include <SDL2/SDL.h>
#include "Graphics.h"

class GameState;

class Game {
public:
    Game();

    bool init(GameState* state);
    void loop();

    void pushState(GameState* state);
    void popState();
    void setQuit();
private:
    bool quit { false };

    Graphics graphics;
    SDL_Event event;
    std::vector<GameState*> states;

    Uint32 new_time;
    Uint32 old_time;

    //internal loop functions
    void update();
    void render();

    void quitGame(); //will free SDL resources and perform cleanup of states
};
#endif

所有MainGame函数都在Gamestate_MainGame.cpp中定义。谢谢你的帮助!

1 个答案:

答案 0 :(得分:6)

virtual void handleEvents(SDL_Event* e) = 0;
                                   ^

是与

不同的原型
void handleEvents(SDL_Event& e);
                           ^

你应该用override标记所有被覆盖的函数,然后编译器会为你做繁重的工作并告诉你是否搞砸了。