为什么不包含文件
Why are the files not being included
这是我第一次用 C++ 尝试一个大项目,我想用 SFML 创建一个游戏。我将我的程序分成了一堆 类,它们相互包含,这就是我出错的地方。
我有三个主要的 类、Game
、State
和 Entity
。 main.cpp
包含 Game.h
文件并开始游戏。 Game.h
文件是所有 SFML 包含的地方。这是我的代码的简化版本。
main.cpp
#include "Game.h"
int main()
{
// starts the game here
}
Game.h
#ifndef GAME_H
#define GAME_H
#include "State.h"
// All the SFML includes and other standard library includes are here
class Game
{
}
#endif
State.h
#ifndef STATE_H
#define STATE_H
#include "Entity.h"
class State
{
}
#endif
Entity.h
#ifndef ENTITY_H
#define ENTITY_H
#include "Game.h"
class Entity
{
}
#endif
理论上,State.h
应该能够访问 SFML 函数,因为它包含 Entity.h
,其中包含 Game.h
,其中包含 SFML。但是,当我将 SFML 函数添加到 State.h
和 Entity.h
中时,visual studio 在我编译它之前不会显示任何错误,它表示函数未定义。
您有一个包含周期:
Game.h 包括 state.h 其中包括 entity.h 其中包括 game.h.
你需要想办法打破这个循环。通常,您通过 header:
中的前向声明来做到这一点
class State;
然后在 .cpp 文件中包含 .h。
这是我第一次用 C++ 尝试一个大项目,我想用 SFML 创建一个游戏。我将我的程序分成了一堆 类,它们相互包含,这就是我出错的地方。
我有三个主要的 类、Game
、State
和 Entity
。 main.cpp
包含 Game.h
文件并开始游戏。 Game.h
文件是所有 SFML 包含的地方。这是我的代码的简化版本。
main.cpp
#include "Game.h"
int main()
{
// starts the game here
}
Game.h
#ifndef GAME_H
#define GAME_H
#include "State.h"
// All the SFML includes and other standard library includes are here
class Game
{
}
#endif
State.h
#ifndef STATE_H
#define STATE_H
#include "Entity.h"
class State
{
}
#endif
Entity.h
#ifndef ENTITY_H
#define ENTITY_H
#include "Game.h"
class Entity
{
}
#endif
理论上,State.h
应该能够访问 SFML 函数,因为它包含 Entity.h
,其中包含 Game.h
,其中包含 SFML。但是,当我将 SFML 函数添加到 State.h
和 Entity.h
中时,visual studio 在我编译它之前不会显示任何错误,它表示函数未定义。
您有一个包含周期:
Game.h 包括 state.h 其中包括 entity.h 其中包括 game.h.
你需要想办法打破这个循环。通常,您通过 header:
中的前向声明来做到这一点class State;
然后在 .cpp 文件中包含 .h。