【问题标题】:C++: circular dependency issueC++:循环依赖问题
【发布时间】:2013-05-07 13:24:11
【问题描述】:

我遇到了循环依赖的问题,我想这是以错误的方式引入 Game 类的设计缺陷。

游戏.h:

#pragma once
#include <SFML\Graphics.hpp>

#include "GameScreen.h"
#include "TitleScreen.h"

class Game
{
protected:
    sf::RenderWindow window;

    GameScreen* CurrentGameScreen;
    TitleScreen Title;

public:
    Game(void);
    ~Game(void);

    sf::RenderWindow getWindow(void);

    void Run();
    void Close();
};

GameScreen.h:

#pragma once

#include "Game.h"

class GameScreen
{
public:
    GameScreen(void);
    ~GameScreen(void);

    virtual void LoadAllResources() {};
    virtual void DrawScreen(Game* game) {};
    virtual void Update(Game* game) {};
};

TitleScreen.h:

#pragma once
#include <SFML\Graphics.hpp>

#include "GameScreen.h"

class TitleScreen : public virtual GameScreen
{
private:
    sf::Texture title_screen;
    sf::Sprite titleScreen;

    sf::Font font;
    sf::Text menuExit;

public:
    TitleScreen(void);
    ~TitleScreen(void);

    void LoadAllResources();
    void DrawScreen(Game* game);
    void Update(Game* game);
};

然后是主文件:

#include "Game.h"

int main()
{
    Game game;
    game.Run();

    //sf::RenderWindow window(sf::VideoMode(800, 600), "Test");

    //GameScreen* currentScreen;
    //TitleScreen titleScreen;

    //currentScreen = &titleScreen;

    //while (window.isOpen())
    //{
    //  currentScreen->Update(&window);
    //  currentScreen->DrawScreen(&window);
    //}

    return 0;
}

GameScreen.hTitleScreen.h 提出了一些 C2061。据我了解,这些是由 Game.h 和 Gamescreen.h 之间的循环依赖引起的。

TitleScreen.h 给了我 error C2504: 'GameScreen' : base class undefined

Game.h:在第 12 和 13 行,给出 C2143: syntax error : missing ';'在“*”之前,虽然我不确定这是从哪里来的,而且我的 IDE 没有给我任何语法错误。

如果我从 GameScreen.h 中删除 #include 语句并将其替换为前向声明 class Game;(我猜这会破坏循环依赖?)以上大部分问题都已解决,但 TitleScreen.cpp 抛出一组 C2027C2227C2228未定义类型左侧 - >left of .) 每次我尝试访问 Game 对象时。 IntelliSense 指出不允许指向不完整类的指针

我在引入 Game 类之前就已经开始工作了——DrawScreen()Update() 将把指向窗口的指针 (sf::RenderWindow* window) 作为参数。 main.cpp 中还有一部分旧代码。

【问题讨论】:

标签: c++ circular-dependency


【解决方案1】:

GameScreen.h 中你应该声明Game 类而不是包含它的整个头文件,所以这样:

class Game;

代替:

#include "Game.h"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多