C++方法声明,类定义问题

Joh*_*ra. 0 c++ declaration definition forward-declaration

我有两个类:A和B.类A的一些方法需要使用类B而相反(类B有需要使用类A的方法).

所以我有:

class A;

class B {

   method1(A a) {
   }

}

class A {

   method1(B b) {
   }

   void foo() {
   }
}
Run Code Online (Sandbox Code Playgroud)

一切正常.

但是当我尝试从B :: method1调用类A的foo()时:

class B {

   method1(A a) {
      a.foo();
   }

}
Run Code Online (Sandbox Code Playgroud)

我得到的结果是前向声明的编译错误和 不完整类型的使用.但为什么会这样呢?(我在使用之前已经宣布了A级?)

Cha*_*via 6

编译器A在您调用的位置没有看到定义A::foo().您不能为不完整类型调用方法 - 即编译器尚不知道其定义的类型.在编译器可以看到定义,您需要定义调用方法class A.

class A;

class B 
{
    public:
   void method1(A a);
};

class A 
{
    public:
   void method1(B b) { }

   void foo() { }
};

void B::method1(A a)
{
    a.foo();
}
Run Code Online (Sandbox Code Playgroud)

实际上,您可能希望将定义B::method1()放在单独的cpp文件中,该#include文件包含用于头文件的文件class A.