代码之家  ›  专栏  ›  技术社区  ›  drahnr

C++类,它的基类和循环include包括[重复]

  •  0
  • drahnr  · 技术社区  · 16 年前

    #ifndef FOO_H_
    #define FOO_H_
    #include "baseclass.h"
    #include "bar.h"
    class Bar;
    class Foo : public baseclass {
    public:
    bar *varBar;
    };
    #endif
    

    文件#2(bar.h):

    #ifndef BAR_H_
    #define BAR_H_
    #include "foo.h"
    class Foo;
    class Bar {
    public:
    Foo *varFoo;
    };
    #endif
    

    #ifndef BASECLASS_H_
    #define BASECLASS_H_
    #include "foo.h"
    class Foo;
    class baseclass {
    public:
    list<Foo*> L;
    };
    #endif
    

    class Foo : public baseclass :

    Error: expected class-name before »{« token
    

    如果我添加 class baseclass;

    Error: invalid use of incomplete type »struct baseclass«
    

    问你是否没有得到任何点。我一直试图改变标题的顺序,但到目前为止还没有成功。

    编辑:注意:我使用的是包含防护装置

    5 回复  |  直到 7 年前
        1
  •  4
  •   RedGlyph sumit sonawane    16 年前

    通常的方法是在头文件周围添加以下内容:

    #ifndef FOO_H_
    #define FOO_H_
    #include "baseclass.h"
    #include "bar.h"
    class Bar;
    class Foo : public baseclass {
    public:
    bar *varBar;
    };
    #endif
    

    #ifndef BAR_H_
    #define BAR_H_
    #include "foo.h"
    class Foo;
    class Bar {
    public:
    Foo *varFoo;
    };
    #endif
    

    大多数编译器(gcc、VC)也接受 #pragma once 在文件的开头,但我很确定它不是当前C++标准的一部分。


    编辑:

    果然,正如ISO/IEC 14882所述,一个#pragma” causes the implementation to behave in an implementation-defined manner. Any pragma that is not recognized by the implementation is ignored. "

    所以我会坚持第一种老式的方法;-)

        2
  •  3
  •   Pete Kirkham    16 年前

    你似乎发布了一个 Bar 成员在 Foo 和a 成员在 酒吧 。这是一种循环依赖,你需要打破它——如果每一个 包含a 酒吧 那么构建要么永远不会终止。

    class Foo : public baseclass {
        public:
            Bar varBar;
    };
    
    class Bar {
        public:
            Foo varFoo;
    };
    

    相反,您需要使用指针或引用 酒吧

    class Bar;
    class Foo : public baseclass {
        public:
            Bar& varBar;
    };
    
    class Bar {
        public:
            Foo varFoo;
    };
    

    由于循环被打破,你只使用了对对象的引用,你不需要对引用的类型有完整的定义,可以使用正向声明。

        3
  •  2
  •   Billy ONeal IS4    16 年前

    class b; 消除了对 #include "b.h" 在文件1中。同样地, #include "a.h" 应该从FILE2中删除。

        4
  •  2
  •   Zoli    16 年前
    #ifndef _BAR_H_
    #define _BAR_H_    
    #include "baseclass.h"
    
    class Bar;
    class Foo : public baseclass {
    public:
        Bar *varBar;
    };
    
    #endif
    

    如果一个类是前向声明的,而你只使用了一个指针或对该类成员的引用,那么你就不需要包含它的头。其他文件中的类也是如此。但是,是的,请确保在所有头文件中都使用include保护程序( #ifndef...#endif

        5
  •  0
  •   dave4420    16 年前

    baseclass.h 不需要任何东西 foo.h ,因此删除 #include "foo.h" 中产阶级。h .

    Foo 变量在你的 Bar 和a 酒吧 在你的 这行不通:你不能把鸡蛋放在盒子里 鸡蛋里的盒子。其中一个或两个应该是指针。