如何在 C++ 中创建两个相互用作数据的类?

How to create two classes in C++ which use each other as data?(如何在 C++ 中创建两个相互用作数据的类?)

本文介绍了如何在 C++ 中创建两个相互用作数据的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建两个类,每个类都包含另一个类类型的对象.我怎样才能做到这一点?如果我不能这样做,是否有解决方法,例如让每个类都包含一个指向其他类类型的指针?谢谢!

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!

这是我所拥有的:

文件: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

文件:ma​​in.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

推荐答案

你不能让两个类直接包含另一种类型的对象,否则你需要为对象提供无限空间(因为 foo 有一个 barfoo 有一个酒吧等)

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:

#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需要bar需要foo需要bar"的引用循环.

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."

这篇关于如何在 C++ 中创建两个相互用作数据的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 C++ 中创建两个相互用作数据的类?

基础教程推荐