[英]Why does a forward declaration not fix the circular dependency?
I have three classes: a TopClass
which contains an instance of a BottomClass
pointer. 我有三个类:一个
TopClass
,它包含一个BottomClass
指针的实例。 The BottomClass
contains a pointer to a HelperClass
. 该
BottomClass
包含一个指向一个HelperClass
。 The HelperClass
keeps a pointer to the TopClass
. 该
HelperClass
保持一个指针TopClass
。 Circular dependency pops up and a forward declaration is needed in the HelperClass
. 循环依赖项弹出,并且在
HelperClass
需要前向声明。
All of this is illustrated with the following code snippets: 以下代码段说明了所有这些:
#include "BottomLevel.h"
namespace foo
{
class TopLevel
{
private:
BottomLevel* item;
};
}
- --
#include "HelperClass.h"
namespace foo
{
class BottomLevel
{
private:
HelperClass* item;
};
}
- --
class TopLevel; // forward declaration here
namespace foo
{
class HelperClass
{
public
HelperClass(TopLevel* item);
};
}
The issue comes when trying to do things in the implementation file. 尝试在实现文件中执行操作时会出现问题。 If I
#include "TopClass.h"
in the cpp file, I get compilation errors stating "overloaded member function not found -- use of undefined type ' TopLevel
'" (ERRORS C2511 and C2027). 如果我在cpp文件中
#include "TopClass.h"
,则出现编译错误,指出“找不到重载的成员函数-使用未定义的类型' TopLevel
'”(错误C2511和C2027)。
Then, if I don't do the #include
I'm still left with C2027 errors because I try to use the forward declared type. 然后,如果我不执行
#include
,则仍然会遇到C2027错误,因为我尝试使用正向声明的类型。
I just know there is a method to fix this, I'm sure I've done it before, but I can't for the life of me remember what I'm supposed to do. 我只知道有一种方法可以解决此问题,我确定我之前已经做过,但是我无法终生记住我应该做的事情。 Any help please?
有什么帮助吗?
The problem is that you're forward declaring TopLevel
outside the foo
namespace so the compiler is never finding the class foo::TopLevel
. 问题是您要在
foo
命名空间之外向前声明TopLevel
,因此编译器永远不会找到foo::TopLevel
类。
Try moving the forward declaration of TopLevel
inside the foo
namespace. 尝试在
foo
名称空间中移动TopLevel
的前向声明。
You need a forward declaration of the form 您需要表格的前向声明
namespace foo {
class TopLevel;
class BottomLevel;
class HelperClass;
}
Then the order wont matter [because you use pointers] 然后顺序就无关紧要了(因为您使用了指针)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.