C++中两个类相互include的问题

在构造自己的类时,有可能会碰到两个类之间的相互引用问题,例如:定义了类A类B,A中使用了B定义的类型,B中也使用了A定义的类型

例如:

Cup.h

#ifndef CUP_H
#define CUP_H

#include "Box.h"

class Cup
{
    public:
        ~Cup();
        Box b;
        Cup();
};

#endif // CUP_H

Cup.cpp

#include "Cup.h"
#include <iostream>

using namespace std;

Cup::Cup()
{
    cout << "Cup cons" << endl;
}

Cup::~Cup()
{
    cout << "Cup des" << endl;
}

Box.h

#ifndef BOX_H
#define BOX_H

#include "Cup.h"

class Box
{
    public:
        Box();
        ~Box();
        Cup cup;
};

#endif // BOX_H

Box.cpp

#include "Box.h"

#include <iostream>

using namespace std;

Box::Box()
{
    cout << "Box cons" << endl;
}

Box::~Box()
{
    cout << "Box des" << endl;
}

在这种情况下,想想可以有b.cup.b.cup.b.....…………,这种定义方式类同程序中的死循环。编译器肯定会报错的。

我的报错信息是

includeCup.h|10|error: 'Box' does not name a type|

所以,一般来说,两者的定义,至少有一方是使用指针,或者两者都使用指针,但是决不能两者都定义实体对象。

言归正传,那么,在定义时因为相互引用肯定会需要相互包含头文件,如果仅仅只是在各自的头文件中包含对方的头文件,是通不过编译的,如上面的情况所示

解决的办法,让其中一个(例如Cup)只声明对方(class Box;)并且使用指针(Box *b),并且不包含头文件Box.h,在实现文件(Cup.cpp)文件中再包含Box.h,修改后的代码如下:

Cup.h

#ifndef CUP_H
#define CUP_H

class Box;

class Cup
{
    public:
        void createBox();
        ~Cup();
        Box *b;
        Cup();
};

#endif // CUP_H

Cup.cpp

#include "Cup.h"
#include <iostream>

#include "Box.h"

using namespace std;

Cup::Cup(): b(NULL)
{
    cout << "Cup cons" << endl;
}

Cup::~Cup()
{
    if (b!=NULL) delete b;
    cout << "Cup des" << endl;
}

void Cup::createBox() {
    b = new Box();
}

注意为什么不在Cup::Cup()中直接b = new Box(),因为这是死循环,直接*,所以使用了createBox()

最后再写一个main.cpp来测试,可以去尝试解释一下运行结果

#include "Box.h"
#include "Cup.h"

#include <iostream>

using namespace std;

int main() {
    Box b;
    cout << "something in the middle" << endl;
    Cup c;
    c.createBox();
}