C++ 头文件重定义错误

use*_*901 2 c++ opengl header-files

我正在 openGl 中创建一个游戏,但我遇到了一个问题,这个问题困扰了我近 2 个小时。主要功能在包含 World.h 的 readobj.cpp 中,我有一个使用 Ball.h 和 Stick.h 的 World.h 文件。另一方面,Ball.h 和 Stick.h 都在使用 Game.h 文件。

世界.h

#include "Ball.h"
#include "Camera.h"
#include "Stick.h"
class World
{
Ball ball[15];
Ball qBall;
Camera camera;
public:
World();
void update();
void render();
};
Run Code Online (Sandbox Code Playgroud)

棒.h

#include "Game.h"
class Stick
{
point power;
public:
void setPosition(point);
void setPower(point);
void render();
void update();
};
Run Code Online (Sandbox Code Playgroud)

球.h

#include "Game.h"
class Camera
{
public:
Camera();
void update();
void render();
};
Run Code Online (Sandbox Code Playgroud)

游戏.h

class point {
public:
double x,y,z;
};
Run Code Online (Sandbox Code Playgroud)

我得到的错误是

g++ -Wall -c readobj.cpp -L. -lBall -lWorld -lCamera -lStick
In file included from Camera.h:1:0, from World.h:2,         from readobj.cpp:12:
Game.h:1:7: error: redefinition of ‘class point’
Game.h:1:7: error: previous definition of ‘class point’
In file included from Stick.h:1:0,
                 from World.h:3,
                 from readobj.cpp:12:
Game.h:1:7: error: redefinition of ‘class point’
Game.h:1:7: error: previous definition of ‘class point’
Run Code Online (Sandbox Code Playgroud)

πάν*_*ῥεῖ 5

使用包括守卫!

示例:

世界.h:

#ifndef WORLD_H     // <<<<<<<<< Note these preprocessor conditions
#define  WORLD_H
#include "Ball.h"
#include "Camera.h"
#include "Stick.h"
class World
{
    Ball ball[15];
    Ball qBall;
    Camera camera;
public:
    World();
    void update();
    void render();
};
#endif // WORLD_H
Run Code Online (Sandbox Code Playgroud)

说明:
如果头文件包含在其他头文件中,并且这些头文件在编译单元中冗余出现,您将收到这些“重新定义” / “重新声明”错误。如上所示,
所谓的包含保护条件,防止预处理器多次渲染包含的代码,从而导致此类错误。