SDL 代码编译但 window 不显示

SDL code compiles but the window doesn't show up

window 可以正常打开,但在更改了一些变量名称后,它简单地没有显示出来。我无法撤消更改,因为我已尝试重新启动 PC。

我正在使用 Microsoft Visual Studio 2013 Professional、msvc2012 plus SDL2 和 SDL_Image。 不知道这是否重要,但笔记本电脑的配置是:i7、8gb ram,windows 8.1 pro,gtx 850M 4gb vram。

代码如下:

Game.h

#ifndef GAME_H
#define GAME_H

#include "SDL.h"

class Game
{
public:
    Game();
    ~Game();
    bool init(const char* title, int xpos, int ypos, int width, int height, int flags);
    void render();
    void update();
    void handleEvents();
    void clean();
    bool running() { return gameRunning; }
private:
    SDL_Window * window;
    SDL_Renderer * renderer;
    SDL_Rect * player;

    bool gameRunning;
};


#endif

Game.cpp

#include "Game.h"

Game::Game()
{
    player->x = 0;
    player->y = 0;
    player->w = 32;
    player->h = 32;
}

Game::~Game()
{

}

bool Game::init(const char* title, int xpos, int ypos, int width, int height, int flags)
{
    if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
    {
        window = SDL_CreateWindow(title, xpos, ypos, width, height, flags);
        if (window != 0)
        {
            renderer = SDL_CreateRenderer(window, -1, 0);
            if (renderer != 0)
            {
                SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
            }
            else { return false; }
        } else { return false; }
    } else { return false; }

    gameRunning = true;

    return true;
}

void Game::render()
{
    SDL_RenderClear(renderer); 

    //SDL_RenderFillRect(renderer, &*player);

    SDL_RenderPresent(renderer);
}

void Game::handleEvents()
{
    SDL_Event event;
    if (SDL_PollEvent(&event))
    {
        switch (event.type)
        {
        case SDL_QUIT:
            gameRunning = false;
            break;
        default:
            break;
        }
    }
}

void Game::clean()
{
    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);
    SDL_Quit();
}

void Game::update()
{

}

main.cpp

#include "Game.h"

Game* game;
int main(int argc, char* argv[])
{
    game = new Game();
    game->init("Lumia", 100, 100, 640, 480, 0);
    while (game->running())
    {
        game->handleEvents();
        game->update();
        game->render();
    }
    game->clean();
    return 0;
}

在你的classGame中,player是一个指针。

当你

Game::Game()
{
    player->x = 0;
    player->y = 0;
    player->w = 32;
    player->h = 32;
}

指针 player 从未被初始化,它没有指向有效的对象,所以你不能取消引用它或者这是未定义的行为(这可能是你的调试器停止的原因)。

你需要先构造player,然后再尝试赋值给它,就像你在尝试使用它之前在main中构造一个新的Game一样。