2011-04-04 115 views
11

我知道循环依赖关系,但即使有前向声明,我也会得到这个区域。 我在做什么错?不完整类型结构的使用无效,即使有前向声明

// facility.h 
class Area; 

class Facility { 
public: 
    Facility(); 
    Area* getAreaThisIn(); 
    void setAreaThisIsIn(Area* area); 
private: 
    Area* __area; 
}; 

// facility.cpp 
#include "facility.h" 
#include "area.h" 
{ ... } 

// area.h 
class Facility; 
class Area { 
public: 
    Area(int ID); 
    int getId(); 

private: 
    std::list<Facility*> _facilities; 
}; 

// area.cpp 
#include "area.h" 
#include "facility.h" 

所以这个编译罚款,但如果我不

// foo.h 
#include "facility.h" 
class Foo { .. }; 

// foo.cpp 
#include "foo.h" 
void Foo::function() { 
    Facility* f = new Facility(); 
    int id = f->getAreaThisIsIn()->getId(); 

当我invalid use of incomplete type struct Area

+3

您是否在您定义的'Foo :: function()'的任何文件中包含了** area.h **? – 2011-04-04 19:30:40

+0

我修正了'facility.h'中的'getAreaThisIn()'输入错误(应该是'getAreaThisIsIn()')并且修正了g ++(在'Facility'和'Area'方法的存根定义中添加了')它为我编译。虽然我的'Foo.cpp'确实包含了两个头文件。 – QuantumMechanic 2011-04-04 19:40:36

+3

请注意,以两个下划线开头的标识符(我在看你的'__area')由实现保留,不应使用。 – 2011-04-04 19:41:00

回答

8

Facility* f = new Facility();,你需要一个完整的声明,而不是向前声明。

+0

你是什么意思?我认为在cpp中包括足够好? – robev 2011-04-04 19:34:47

+1

@robev包括'facility.h'应该工作得很好,除非有其他错误。 – 2011-04-04 19:36:25

+1

@robev - 如果显示“Foo”类标题及其源文件,事情就会清除。 – Mahesh 2011-04-04 19:36:31

4

你是否在foo.cpp中包含area.h和facility.h(假设这是你得到错误的文件)?

+0

不,我必须包含这两个? – robev 2011-04-04 19:35:16

+3

是的,因为您在代码中为Area和Facility实例调用成员函数,所以您必须。 – 2011-04-04 19:39:21

19

澄清:一个向前声明允许您在非常有限的方式在对象上进行操作:

struct Foo; // forward declaration 

int bar(Foo* f); // allowed, makes sense in a header file 

Foo* baz(); // allowed 

Foo* f = new Foo(); // not allowed, as the compiler doesn't 
        // know how big a Foo object is 
        // and therefore can't allocate that much 
        // memory and return a pointer to it 

f->quux(); // also not allowed, as the compiler doesn't know 
      // what members Foo has 

正向声明可以在某些情况下帮助。例如,如果头部中的函数只接受指向对象的指针而不是对象,则不需要整个头部的类定义。这可以改善您的编译时间。但是这个头文件的实现几乎可以保证需要相关的定义,因为你可能想要分配这些对象,调用这些对象的方法等等,并且你需要的不仅仅是一个前向声明。

相关问题