C++ C+中的共存类+;

C++ C+中的共存类+;,c++,class,design-patterns,object,C++,Class,Design Patterns,Object,我需要创建两个类,它们相互使用 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 { priv

我需要创建两个类,它们相互使用

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;
};
例如:

A类
包含类型为
B类
的对象,而
B类
包含类型为
A类

<>但是,当我编译时,这就是发生的事情:“错误:ISO C++禁止声明“map”没有类型“< /p>” 我修改了我的类,以保持头(.h)文件分开,但它没有解决

也许,这是一个基本的问题,但我不知道在谷歌上搜索的关键词

代码:

第h单元:

Class Cell
{
public:
    Map *map;
}
地图h:

Class Map
{
public:
    Cell *cell;
}

在您的例子中,问题是您有递归包含
Cell.h
包括
Map.h
,其中包括
Cell.h
。与其像这样包含,不如向前声明类:

单元格.h中

class Map;

class Cell
{
    // ...
}
class Cell;

class Map
{
    // ...
}
Map.h
中:

class Map;

class Cell
{
    // ...
}
class Cell;

class Map
{
    // ...
}
您需要向前声明和指针

//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;
}

如果
A类
包含
B类
,而
B类
也包含
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;
};

“包含”是什么意思?显然,
A
B
不能将彼此的实例作为成员…是的,他们可以@OliCharlesworth…@IvanSeidel:他们绝对不能,因为这会导致无限递归。但是,它们可以是指向或引用彼此实例的成员(例如,通过
映射
)。您发布了指向代码而非代码的链接。一个好问题有一个简化版的代码,它仍然演示了您想要讨论的问题。另请参见。@IvanSeidel它们不能包含彼此的实例。它们所能做的最好的事情就是保存指向其他实例的引用或指针。这是非常不同的共享指针将是一个更好的选择,虽然要小心循环引用。是的,但只是保持它的轻/简单的例子啊,人来了一个家伙。。。没什么大不了的。对于一个简单的例子来说,太多的混乱。另外,用户尚未指定C++11或boost的可用性。。。