c++ default-int 中的语法错误

Syntax error in c++ default-int

所以我刚开始用 C++ 编程,我打算制作一个小游戏作为我的第一个项目(使用 SDL 库)。

所以我在头文件中有这么一小段代码,它给了我一个我无法解决的错误。

main.h

#include "Screen.h"
#include "MainGame.h"

Screen* screen = nullptr; //main.h line 8

Screen.h

#pragma once

#include "SDL.h"
#include <string>
#include <stdio.h>
#include <iostream>
#include "GameState.h"
#include "Game.h"
using namespace std;

class Screen
{

public:
    Screen(string name, int width, int height, GameState* state);
    ~Screen();
    SDL_Window *window;
    SDL_Surface *screen;
    SDL_Renderer *renderer;
};

MainGame.h

#pragma once
#include "GameState.h"
#include <stdio.h>

class MainGame :
    public GameState
{
public:
    MainGame();
    ~MainGame();
    void start();
    void update();
    void render();
    void stop();
};

Game.h

#pragma once
#include "GameState.h"
#include "Screen.h"
#include "SDL.h"
#include "main.h"

class Game
{
public:
    GameState* activestate;
    Game(GameState state);
    ~Game();
    void changeState(GameState newState);
    bool isRunning;
    void handleEvents();
    void update();
    void render();
    void stop();
};

GameState.h

#pragma once
class GameState
{ 
public:
    GameState();
    ~GameState();
    virtual void start();
    virtual void update();
    virtual void stop();
    virtual void render();
};

它给出了这个错误:

Error   C2143   syntax error: missing ';' before '* main.h  8

Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int    main.h  8   

这些错误是什么意思,我该如何解决?

错误来自您的循环依赖。一些文件包括 Screen.h。 Screen.h 包括 Game.h。 Game.h 包括 main.h。 main.h 需要 Screen.h 但由于 pragma once 不能包含它。所以它不知道 class 屏幕。要么删除循环依赖(如果可能的话更好的解决方案,这里是可能的):

在 Game.h

中删除 #include "main.h"

或使用前向声明:

在main.h中写入class Screen;:7