问题描述
我正在使用visual studio 2010开发一个C ++程序。我有这些类定义&头文件:$ b $bÁ
sh:
类s:oe {
...
};
th:
class t:oe {
...
};
oe.h:
class oe {
...
o getO(); //我们引用oe.h中的类'o',所以我们必须包含oh beore oe.h
};
&哦:
class o {
...
s getS(); //我们引用类's'在哦,所以我们必须包括sh begore哦
};
问题是我们引用 oe.h中的类'o'
,因此我们必须在 oe.h
之前加入 oh
我们还引用 oh
中的类's,因此我们必须在之前加入
,但我们不能这样做,因为 sh
sh
需要 oe.h
oe.h
需要 o.h
& o.h
需要 s.h
!
\\
正如你所看到的,在类依赖循环中存在某种类型的循环。所以我不能编译项目。如果我删除s.h& t.h& oe.h,问题会解决(这里是 stdafx.h
这个状态):
#includesh
#includeth
#includeoh
#includeoe.h
但我必须使用所有给定的依赖关系&我不能删除任何依赖项。任何想法?
您可以使用转发声明解决这个问题,
不要在 s
中添加标题,而是先声明:
class s;
,你可以将它用作一个不完整的类型,除了类的数据成员。 (前提是实现是分开的)。
这很可能不能解决底层问题 p>
I'm developing a C++ program using visual studio 2010. I've these class definitions & header files :
s.h :
class s : oe {
...
};
t.h :
class t : oe {
...
};
oe.h :
class oe {
...
o getO();//we reference to class 'o' in oe.h, so we must include o.h begore oe.h
};
& o.h :
class o {
...
s getS();//we reference to class 's' in o.h, so we must include s.h begore o.h
};
the problem is that we reference to class 'o' in oe.h
, so we must include o.h
before oe.h
, & also we reference to class 's' in o.h
, so we must include s.h
before o.h
, but we can't do this because s.h
needs oe.h
& oe.h
needs o.h
& o.h
needs s.h
!
As you see, some kind of loop exists in class dependency cycle & so I can't compile the project. If i remove dependency between s.h & t.h & oe.h, the problem will solve (here is stdafx.h
for this state) :
#include "s.h"
#include "t.h"
#include "o.h"
#include "oe.h"
but I have to use all given dependencies & I can't remove anyone of dependencies. any idea?
You can solve this using forward declarations instead and moving implementations to implementation files.
Instead of including a header for s
, just forward declare it:
class s;
and you can use it as an incomplete type for just about anything except a data member of the class. (provided the implementations are separated).
This, most probably, doesn't tackle the underlying problem, which is your design.
这篇关于循环类依赖,同时包括C ++中的头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!