使用不完整类型结构无效,即使使用前向声明也是如此

rob*_*bev 11 c++ forward-declaration

我知道循环依赖,但即使使用前向声明,我也会得到这个区域.我究竟做错了什么?

// 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"
Run Code Online (Sandbox Code Playgroud)

所以这个编译很好,但如果我这样做

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

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

当我得到 invalid use of incomplete type struct Area

Max*_*ert 21

澄清:前向声明允许您以非常有限的方式操作对象:

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
Run Code Online (Sandbox Code Playgroud)

在某些情况下,前向声明可能有所帮助.例如,如果标头中的函数只接受指向对象而不是对象的指针,那么您不需要#include该标头的整个类定义.这可以缩短编译时间.但是这个头的实现几乎可以保证需要#include相关的定义,因为你可能想要分配这些对象,调用那些对象的方法等等,而且你需要的不仅仅是前向声明.


Let*_*_Be 8

因为Facility* f = new Facility();你需要一个完整的声明,而不仅仅是前方声明.