简体   繁体   English

循环依赖

[英]Circular dependency

I have a class called Point and an other namespace containing a tree class. 我有一个称为Point的类,另一个包含树类的名称空间。 this tree is a balanced binary search tree, and uses the function compare to compare its keys and puts them in the right place. 该树是平衡的二进制搜索树,并使用compare函数比较其关键字并将其放在正确的位置。 My tree contains Point s, and for each point I have to know which tree it belongs to, so I tried to add a pointer to the tree in my Point class like this: 我的树包含Point ,对于每个点我都必须知道它属于哪个树,因此我尝试在Point类中添加一个指向树的指针,如下所示:

class Point{
   public:
   double x, y;
   std::set<std::multiset<Point,Tree::compare()>*>s; //Tree is the name of the namespace
// some other data
}

My problem is that since my tree uses Point.h (because it stores Point s) I cant add LayerThree.h to my it so I cant use Tree::compare() in my Point.h . 我的问题是,由于我的树使用Point.h (因为它存储Point S)我不能添加LayerThree.h我的,所以我不能使用Tree::compare()在我的Point.h I tried to add a new file like cmp.h and put my compare function in it, But It did not help. 我试图添加一个新的文件,如cmp.h然后将我的compare函数放入其中,但这没有帮助。 What should I do? 我该怎么办?

EDIT: I can not put both my tree and my Point class together in the same file because there are other files that needs to include Point.h 编辑:我不能将我的树和Point类放到同一文件中,因为还有其他文件需要包含Point.h

As Jepessen mentioned already you need forward declaration. 正如Jepessen所说,您需要向前声明。 Here is an example: 这是一个例子:

Class A depends on class B AND class B depends on class A, use forward declaration like this: A类依赖于B类,而B类依赖于A类,使用如下的前向声明:

In Class "Bh": 在“ Bh”类中:

#include "A.h"

class B
{
   //Do stuff
};

And in Class "Ah": 在“ Ah”类中:

 // Forward declaration of class B, this tells the compiler to not worry about 
 // class B as somewhere later in compilation class B will be declared
class B;

class A
{
   //Do stuff
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM