如何在C++中创建两个使用彼此作为数据的类?

Ste*_*son 44 c++ pointers class header-files

我正在寻找创建两个类,每个类包含另一个类类型的对象.我怎样才能做到这一点?如果我不能这样做,是否有一个解决方法,比如每个类包含一个指向另一个类类型的指针?谢谢!

这就是我所拥有的:

文件:bar.h

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

文件:foo.h

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

文件:main.cpp

#include "foo.h"
#include "bar.h"

int
main (int argc, char **argv)
{
  foo myFoo;
  bar myBar;
}
Run Code Online (Sandbox Code Playgroud)

$ 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
Run Code Online (Sandbox Code Playgroud)

tem*_*def 97

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

但是,您可以通过让两个类存储指向彼此的指针来实现此目的.为此,您需要使用前向声明,以便两个类知道彼此的存在:

#ifndef BAR_H
#define BAR_H

class foo; // Say foo exists without defining it.

class bar {
public:
  foo* getFoo();
protected:
  foo* f;
};
#endif 
Run Code Online (Sandbox Code Playgroud)

和

#ifndef FOO_H
#define FOO_H

class bar; // Say bar exists without defining it.

class foo {
public:
  bar* getBar();
protected:
  bar* f;
};
#endif 
Run Code Online (Sandbox Code Playgroud)

请注意,两个标头不相互包含.相反,他们只是通过前向声明知道其他类的存在.然后,在这两个类的.cpp文件中,您可以#include使用另一个标头来获取有关该类的完整信息.这些前向声明允许您打破"foo needs bar needs foo needs bar"的引用周期.

  • "foo需要酒吧需要foo需要吧." lawl.= P (10认同)

Ebo*_*ike 5

那没有意义。如果 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
Run Code Online (Sandbox Code Playgroud)