如何在 C++ 中创建两个类哪些互相使用对方作为数据?
我正在创建两个类,每个类都包含另一个类类型的对象。我该怎么做?如果我不能这样做,是否有解决方法,例如让每个类包含指向其他类类型的指针?谢谢!
这是我所拥有的:
文件: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< /em>
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
I'm looking to create two classes, each of which contains an object of the other class type. How can I do this? If I can't do this, is there a work-around, like having each class contain a pointer to the other class type? Thanks!
Here's what I have:
File: bar.h
#ifndef BAR_H
#define BAR_H
#include "foo.h"
class bar {
public:
foo getFoo();
protected:
foo f;
};
#endif
File: foo.h
#ifndef FOO_H
#define FOO_H
#include "bar.h"
class foo {
public:
bar getBar();
protected:
bar b;
};
#endif
File: 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能让两个类直接包含另一种类型的对象,否则你需要为该对象提供无限的空间(因为 foo 有一个 bar,而 foo 有一个 bar,等等)。
你确实可以通过让不过,两个类存储彼此的指针。为此,您需要使用前向声明,以便两个类知道彼此的存在:
并且
请注意,两个标头不互相包含。相反,他们只是通过前向声明知道另一个类的存在。然后,在这两个类的 .cpp 文件中,您可以
#include
另一个标头来获取有关该类的完整信息。这些前向声明允许您打破“foo 需要 bar 需要 foo 需要 bar”的引用循环。You cannot have two classes directly contain objects of the other type, since otherwise you'd need infinite space for the object (since foo has a bar that has a foo that has a bar that etc.)
You can indeed do this by having the two classes store pointers to one another, though. To do this, you'll need to use forward declarations so that the two classes know of each other's existence:
and
Notice that the two headers don't include each other. Instead, they just know of the existence of the other class via the forward declarations. Then, in the .cpp files for these two classes, you can
#include
the other header to get the full information about the class. These forward declarations allow you to break the reference cycle of "foo needs bar needs foo needs bar."这没有道理。如果A包含B,B包含A,那么它的大小将是无限的。想象一下有两个盒子并试图将它们放入彼此中。不起作用,对吧?
指针仍然有效:
That doesn't make sense. If A contains B, and B contains A, it would be infinite size. Imagine putting having two boxes and trying to put both into each other. Doesn't work, right?
Pointers work though: