C++头文件 - 困惑!

5 c++ header-files

game.h needs:
- packet.h
- socket.h

server.h needs:
- socket.h

socket.h needs:
- game.h
Run Code Online (Sandbox Code Playgroud)

当我尝试将socket.h包含到game.h中时会出现问题,因为socket.h已经包含了game.h.我该如何解决这些问题?

ang*_*son 17

通常的方法是在头文件中使用#ifdef和#define

在game.h内:

#ifndef GAME_H
#define GAME_H

.. rest of your header file here

#endif
Run Code Online (Sandbox Code Playgroud)

这样,内容将被多次读取,但只定义一次.

编辑:删除每个注释的标识符开头和结尾的下划线.


Kon*_*lph 9

关键是前瞻性声明.从中获取game.h所需的东西socket.h(或反之亦然)并在另一个标题中向前声明它,例如game_forwards.h.例如,请考虑以下事项:

// game_fwd.h

#ifndef GAME_FWD_H
#define GAME_FWD_H

class game;

#endif // ndef GAME_FWD_H

// game.h

#ifndef GAME_H
#define GAME_H

#include "socket.h"

class game {
    socket* m_sck;
};

#endif // ndef GAME_H

// socket.h

#ifndef SOCKET_H
#define SOCKET_H

#include "game_fwd.h"

class socket {
    game* m_game;
};

#endif // ndef SOCKET_H
Run Code Online (Sandbox Code Playgroud)

显然,为了实现这一点,将接口和实现分开是很重要的.


Pet*_*ham 8

除了技术(前向定义和一次读取头)之外,您还需要弄清楚套接字头为什么需要游戏头中的任何内容,并将系统打包成具有单个依赖顺序的模块.套接字类不应该有任何理由知道它正在使用什么游戏.