如何声明彼此引用的类?

Wit*_*eso 2 c++ reference class include

自从我完成C++以来已经很长时间了,我遇到了相互引用类的麻烦.

现在我有类似的东西:

class a
{
  public:
    a();
    bool skeletonfunc(b temp);
};
Run Code Online (Sandbox Code Playgroud)

BH

class b
{
  public:
    b();
    bool skeletonfunc(a temp);
};
Run Code Online (Sandbox Code Playgroud)

由于每个人都需要引用另一个,我发现我不能在顶部做彼此的#include,或者我最后在包含的奇怪的循环中.

那么,如何让这个a可以使用b并且没有发生周期性的#include问题反之亦然?

谢谢!

Ree*_*sey 8

你必须使用前瞻声明:

class b;
class a
{
  public:
    a();
    bool skeletonfunc(b temp);
}
Run Code Online (Sandbox Code Playgroud)

但是,在许多情况下,这可能会强制您使用方法调用或成员变量中的引用或指针,因为您不能在两个类头中都有完整类型.如果必须知道类型的大小,则需要使用引用或指针.但是,如果只需要方法声明,则可以使用该类型.

  • 不,原始声明(使用按值传递语义)将编译.在方法定义之前,您将需要完整的类声明,但不要声明方法签名:`class a; void f(a); class a {}; void f(ax){...`参见http://stackoverflow.com/questions/389957/forward-declaration-of-a-base-class/390124#390124 (6认同)