如何在C ++中使用对方作为数据创build两个类?

我正在寻找创build两个类,其中每个包含其他类types的对象。 我该怎么做? 如果我不能做到这一点,是否有一个解决方法,像每个类包含一个指向其他类types的指针 ? 谢谢!

这是我有:

文件: bar.h

#ifndef BAR_H #define BAR_H #include "foo.h" class bar { public: foo getFoo(); protected: foo f; }; #endif 

文件: foo.h

 #ifndef FOO_H #define FOO_H #include "bar.h" class foo { public: bar getBar(); protected: bar b; }; #endif 

文件: main.cpp

 #include "foo.h" #include "bar.h" int main (int argc, char **argv) { foo myFoo; bar myBar; } 

$ g ++ main.cpp

 In file included from foo.h:3, from main.cpp:1: bar.h:6: error: 'foo' does not name a type bar.h:8: error: 'foo' does not name a type 

你不能让两个类直接包含另一个types的对象,否则你需要无限的空间来存放对象(因为foo有一个带有一个条的foo等)

不过,通过让两个类彼此存储指针,确实可以做到这一点。 要做到这一点,你需要使用前向声明,这样两个类才能知道对方的存在:

 #ifndef BAR_H #define BAR_H class foo; // Say foo exists without defining it. class bar { public: foo* getFoo(); protected: foo* f; }; #endif 

 #ifndef FOO_H #define FOO_H class bar; // Say bar exists without defining it. class foo { public: bar* getBar(); protected: bar* f; }; #endif 

请注意,这两个标题不包含对方。 相反,他们只是通过前瞻性声明了解其他阶级的存在。 然后,在这两个类的.cpp文件中,可以#include包含另一个头以获取有关该类的完整信息。 这些转发声明允许你打破“foo需要吧需要foo需要吧”的引用循环。

这没有意义。 如果A包含B,而B包含A,则它将是无限大小。 想象一下,把两个盒子放在一起,试图把两个盒子放在一起。 不行,对不对?

指针工作虽然:

 #ifndef FOO_H #define FOO_H // Forward declaration so the compiler knows what bar is class bar; class foo { public: bar *getBar(); protected: bar *b; }; #endif