即使使用前向声明,也无法有效使用不完整的类型结构
我知道循环依赖,但即使有前向声明,我也能得到这个区域。 我做错了什么?
// 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
I'm aware of circular dependencies, but even with forward declarations I get this area.
What am I doing wrong?
// 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"
So this compiles fine, but if I do
// foo.h
#include "facility.h"
class Foo { .. };
// foo.cpp
#include "foo.h"
void Foo::function() {
Facility* f = new Facility();
int id = f->getAreaThisIsIn()->getId();
When I get invalid use of incomplete type struct Area
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
澄清一下:前向声明允许您以非常有限的方式操作对象:
前向声明在某些情况下可以提供帮助。例如,如果标头中的函数仅采用指向对象的指针而不是对象,那么您不需要
#include
该标头的整个类定义。这可以缩短您的编译时间。但是该标头的实现几乎肯定需要#include
相关定义,因为您可能想要分配这些对象、调用这些对象的方法等,并且您需要的不仅仅是一个前瞻性声明来做到这一点。To clarify: a forward declaration allows you to operate on an object if very limited ways:
Forward declarations can help in some cases. For instance, if the functions in a header only ever take pointers to objects instead of the objects, then you don't need to
#include
the whole class definition for that header. This can improve your compile times. But the implementation for that header is almost guaranteed to need to#include
the relevant definition because you're likely going to want to allocate those objects, call methods on those objects, etc. and you need more than a forward declaration to do that.对于
Facility* f = new Facility();
您需要完整的声明,而不仅仅是前向声明。For
Facility* f = new Facility();
you need a full declaration, not just forward declaration.您是否在 foo.cpp 中#include了area.h和facility.h(假设这是您收到错误的文件)?
Did you #include both area.h and facility.h in foo.cpp (assuming this is the file where you get the error)?