【问题标题】:Cyclic class dependency while including header files in C++循环类依赖,同时在 C++ 中包含头文件
【发布时间】:2012-06-29 19:49:33
【问题描述】:

我正在使用 Visual Studio 2010 开发 C++ 程序。我有这些类定义和头文件:
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
};

&哦:

class o {
    ...
    s getS();//we reference to class 's' in o.h, so we must include s.h begore o.h 
};

问题是我们在oe.h中引用了类'o',所以我们必须在oe.h之前包含o.h,而且我们在o.h中引用了类's',所以我们必须包含@ 987654330@ 在o.h 之前,但我们不能这样做,因为s.h 需要oe.hoe.h 需要o.ho.h 需要s.h
如您所见,类依赖循环中存在某种循环,因此我无法编译该项目。如果我删除 s.h & t.h & oe.h 之间的依赖关系,问题就会解决(这里是 stdafx.h 表示这个状态):

#include "s.h"
#include "t.h"
#include "o.h"
#include "oe.h"

但是我必须使用所有给定的依赖项并且我不能删除任何依赖项。有什么想法吗?

【问题讨论】:

标签: c++ class header include dependencies


【解决方案1】:

前向声明不仅适用于返回值的指针/引用。

所以,你可以这样做:

oe.h:

class o;

class oe {
    o getO();
};

oe.cpp:

#include "oe.h"
#include "o.h"

o oe::getO() {
    return o();
}

根据需要冲洗并重复...由于您在 .h 文件中不再有 #includes,因此没有机会循环包含依赖项。

【讨论】:

  • 你还应该添加 'public:' 关键字
【解决方案2】:

您可以改用前向声明并将实现移至实现文件来解决此问题。

不要包含s 的标头,只需转发声明即可:

class s;

并且您可以将它用作除了类的数据成员之外的任何东西的不完整类型。 (前提是实现是分开的)。

这很可能无法解决根本问题,这是您的设计。

【讨论】:

  • 如果可以的话,我会为最后一行添加 +1!
猜你喜欢
  • 2011-07-11
  • 2012-02-19
  • 2015-07-25
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多