【问题标题】:Cross reference and circular dependency. Header including itself indirectly交叉引用和循环依赖。标头间接包括自身
【发布时间】:2011-12-23 19:24:54
【问题描述】:

可放置的.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中包含这个新头文件。

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

【问题讨论】:

    标签: c++ inheritance header circular-dependency cross-reference


    【解决方案1】:

    仅在您必须

    时才包含标题

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

    您只需要包含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;
        ...
    };
    

    附言。添加标题保护。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        #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;
        };
        

        【讨论】:

        • 标题保护只防止多重包含,它们不能保护你免受循环设计的影响。
        • 关于前向引用的信息有帮助吗?你需要头后卫。而且您需要前向引用。
        【解决方案4】:

        有两个问题:

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

        查看更多here

        【讨论】:

          【解决方案5】:

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

          #ifndef PLACEABLE_H
          #define PLACEABLE_H
          
          //
          // Class definitions and function declarations
          //
          
          #endif
          

          【讨论】:

            猜你喜欢
            • 2012-02-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-06
            • 1970-01-01
            • 2012-08-11
            • 2011-07-11
            相关资源
            最近更新 更多