【问题标题】:Recursive Class header include [duplicate]递归类标头包括[重复]
【发布时间】:2015-02-03 01:34:48
【问题描述】:

我需要包含递归类头文件。

“Foo.h”

#ifndef FOO_H
#define FOO_H
#include "Bar.h"

class Foo {
public:
    Bar* barMember;
};
#endif

"Bar.h"

 #ifndef BAR_H
 #define BAR_H
 #include "Foo.h"
 class Bar {
 public:
     Foo* fooMember;
 };
 #endif

在这种情况下,我会遇到类似

的错误

'class' 没有命名类型

考虑在这种情况下Foo 是主类,它包含许多其他类作为成员。但是对于一个成员,我需要进行双向连接。

那我为什么会有这样的问题呢?

【问题讨论】:

    标签: c++ unix recursion header-files


    【解决方案1】:

    使用前向声明:

    #ifndef FOO_H
    #define FOO_H
    
    class Bar;
    
    class Foo
    {
    public:
        Bar* barMember;
    };
    #endif
    

    和:

    #ifndef BAR_H
    #define BAR_H
    
    class Foo;
    
    class Bar
    {
    public:
        Foo* fooMember;
    };
    #endif
    

    您只需要在包含实现的 .cpp 文件中包含相应的头文件,因此不会相互包含。

    【讨论】:

    • 嗯,谢谢..你真的节省了我的时间,我太累了......再次感谢
    • 哦,不,再次,我不知道它给了我很多错误。像前向声明........我不知道该怎么办......
    猜你喜欢
    • 2012-08-11
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2019-06-27
    相关资源
    最近更新 更多