【问题标题】:How to create two classes in C++ which use each other as data?如何在 C++ 中创建两个相互用作数据的类?
【发布时间】:2011-06-25 06:27:46
【问题描述】:

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

这是我所拥有的:

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

【问题讨论】:

    标签: c++ class pointers header-files


    【解决方案1】:

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

    不过,您确实可以通过让这两个类存储彼此的指针来做到这一点。为此,您需要使用前向声明,以便两个类知道彼此的存在:

    #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”的引用循环。

    【讨论】:

    • "foo 需要 bar 需要 foo 需要 bar。"法律。 =P
    • 实际上,如果它们只是相互包含,那么没有空间也足够了。但是这种退化的情况是没有用的。所以没有特别规定。
    • 但是我怎样才能在类内部的这些指针的帮助下调用一个方法而不引起错误
    • 编写完两个头文件后,您可以在 .cpp 文件中包含这两个头文件以引入两个类定义。从那里你可以使用任何你想要的成员函数。如果您在执行此操作时遇到问题,请随时发布一个单独的问题来概述您的情况!
    • 哇....这是迄今为止最好的答案。它还允许您在两者中使用每个类的实例。是我一直在寻找的,
    【解决方案2】:

    这没有意义。如果 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2013-09-26
      • 2012-12-22
      • 1970-01-01
      相关资源
      最近更新 更多