C ++中共存的类

时间:2013-06-21 17:21:36

标签: c++ class design-patterns object

我需要创建两个相互使用的类。

例如:

Class A包含Class B类型的对象,Class B包含Class A类型的对象

但是,当我编译时,会发生以下情况:“错误:ISO C ++禁止声明'Map'没有类型”

我修改了我的类,以保持Header(.h)文件分离,但它没有解决。

也许,这是一个基本问题,但我不知道要在Google上搜索的关键字...

代码:

Cell.h:

Class Cell
{
public:
    Map *map;
}

Map.h:

Class Map
{
public:
    Cell *cell;
}

3 个答案:

答案 0 :(得分:3)

您需要转发声明和指针。

//a.h
class B; //forward declare than a class B, exist somewhere, although it is not completely defined.

class A{
 map<string,B*> mapOfB;
};

//b.h
class A; //forward declare than a class A, exist somewhere, although it is not completely defined.
class B{
 map<string,A*> mapOfA;
}

在您的.cxx中,您实际上会包含必要的标题

//a.cxx
#include "b.h"
A::A(){ /* do stuff with mapOfB */ }

//b.cxx
#include "a.h"
B::B(){ /* do stuff with mapOfA */ }

答案 1 :(得分:2)

您的案例中的问题是您有递归包含。 Cell.h包括Map.h,其中包含Cell.h。而不是包括这样只是向前声明类:

Cell.h

class Map;

class Cell
{
    // ...
}

Map.h

class Cell;

class Map
{
    // ...
}

答案 2 :(得分:1)

如果class A包含class Bclass B还包含class A,那么您就不能这样做。

class B; // forward declaration of name only. Compiler does not know how much
         // space a B needs yet.

class A {
    private:
        B b; // fail because we don't know what a B is yet.
};

class B {
    private:
        A a;
};

即使这样可行,也无法构建任何一个实例。

B b; // allocates space for a B
     // which needs to allocate space for its A
     // which needs to allocate space for its B
     // which needs to allocate space for its A
     // on and on...
然而,

可以包含彼此的指针(或引用)。

class B; // forward declaration tells the compiler to expect a B type.

class A {
    private:
        B* b; // only allocates space for a pointer which size is always
              // known regardless of type.

};

class B {
    private:
        A* a;
};