圆形C ++报头包括(Circular C++ Header Includes)

2019-06-18 12:11发布

在一个项目中,我有2类:

// mainw.h

#include "IFr.h"
...
class mainw
{
public:
static IFr ifr;
static CSize=100;
...
};

// IFr.h

#include "mainw.h"
...
class IFr
{
public float[mainw::CSize];
};

但我不能编译这段代码,在得到一个错误static IFr ifr; 线。 就是这种交叉列入禁止?

Answer 1:

就是这种交叉夹杂物被禁止?

是。

一个变通办法是说mainw的IFR成员是引用或指针,使正向声明会做包括完整的声明,等代替:

//#include "IFr.h" //not this
class IFr; //this instead
...
class mainw
{
public:
static IFr* ifr; //pointer; don't forget to initialize this in mainw.cpp!
static CSize=100;
...
}

可替换地,在一个单独的头文件中定义的CSize值(使得Ifr.h可以包括该另一头文件,而不是包括mainw.h)。



Answer 2:

你不能有嵌入对方这样两班。 你可以让他们的指针之一:

class foo;

class bar 
{
    foo* fooPtr;
}

你必须构建foo和它在酒吧的构造函数分配给fooPtr和释放它在析构函数 - 它肯定是多一点的工作。

或者说,在这种情况下,作为评论者的一个建议,让mainw ::尺寸的定义,并把它放在常见。



Answer 3:

你可以做递归包括这样的,但一般而言,您还需要使用某种类型的头文件保护把戏 - 否则,预处理器将进入无限循环。 这不会真正帮助您解决潜在的问题,因为你本质上有两个班,每个需要互相看对方的完整的声明,以便编译:

class mainw
{
public:
static IFr ifr; // needs to see the full declaration of the Ifr class in order to know the size
...

class IFr
{
public float[mainw::size]; // needs to see the full declaration of mainw in order to know what size is

无论你把哪一个第一,因为它需要知道的另一个的全部细节将无法编译。



Answer 4:

那种圆形夹杂的不是由C ++允许的,但这应该工作:

相反,包括IFr.h的,使用前向声明。

class IFr;
class mainw
{
    //...
};

这将使mainw编译就好了,但使用的所有代码ifr成员需要包括IFr.h了。

这只能是因为ifr是一个static成员。 否则,编译器需要知道的确切大小ifr

此外,许多其他的人说,你应该有包括头部周围守卫,以避免来自包括两次相同的标题错误。

#ifndef IFR_H
#define IFR_H
//...
#endif


Answer 5:

你可以做:

// mainw.h

#include "IFr.h"
class mainw {
public:
    static const size_t CSize=100;
    static IFr<CSize> ifr;
...
};

// IFr.h
template <size_t Sz>
struct IFr {
    float sz_[Sz];
};

或者如果需要的CSize在运行时使用,以改变指针解决方案@ChrisW答案节目。



Answer 6:

如果你有

#ifndef __MYHEADER_NAME_WHICH_IS_RANDOM_PER_FILE_H
#define __MYHEADER_NAME_WHICH_IS_RANDOM_PER_FILE_H
//... Code..
#endif

在你的代码包,那么你应该罚款:)

[编辑]代码拼写:o:P



文章来源: Circular C++ Header Includes