4

可放置的.h

#include "selectable.h"

class placeable : selectable
{
..
};

可选择的.h

#include "game.h"


class selectable
{
..
};

游戏.h

#include "placeable.h"

class game
{
...
class placeable* holding;
...
};

基本上placeable.h 包括selectable.h,其中包括game.h,其中又包括placeable.h。

我能想到的唯一解决方案是将placeable*放在一个新的头文件中,使其成为静态/全局的,然后在game.h和selectable.h中包含这个新头文件。

对不起,我在上面的代码中包含了标题保护。我以为这很明显。在这种情况下,由于继承,标头保护没有帮助,前向声明也是如此。

4

5 回答 5

5

仅在必须时才包含标题

使用前向声明优先于包括:

您只需要包含Xiff 类的标题:

  • 你有一个“X”类的成员
  • 你从类'X'派生
  • 您按值传递类“X”的参数。

否则,前向声明就足够了。

//  -> Don't do this #include "placeable.h"
class     placeable;  // forward declare
                      // Fine if you are using a pointer.

class game
{
    ...
    class placeable* holding;
    ...
};

PS。添加标题保护。

于 2011-12-23T19:34:11.697 回答
3

这意味着您没有正确封装设计的功能。应该是高层包含低层,不是同层包含同层。如果游戏是更高级别,则可选不应包括 game.h。

于 2011-12-23T19:30:56.527 回答
2

这是一个已解决的问题。它被称为头后卫。在你的所有头文件中试试这个:

#ifndef __NAMEOFTHEFILE_H__
#define __NAMEOFTHEFILE_H__
// nothing goes above the ifndef above

// everything in the file goes here

// nothing comes after the endif below
#endif

此外,您可以这样做(这称为前向引用):

// game.h

class placeable;

class game { ...
    placeable* p;
};
于 2011-12-23T19:32:45.867 回答
0

有两个问题:

  1. 循环头依赖。解决方案 - #ifndef ...
  2. 为未知类型分配空间。解决方案 - 可放置类;

在这里查看更多

于 2015-03-30T07:24:47.993 回答
-1

在每个头文件中使用头文件保护来避免这个问题。一般来说,你的头文件应该是这样的:

#ifndef PLACEABLE_H
#define PLACEABLE_H

//
// Class definitions and function declarations
//

#endif
于 2011-12-23T19:33:36.417 回答