由于类类型的错误转换,无法通过此操作

kla*_*aus 3 c++ this c++11

我在两个不同的文件中定义了以下两个类:

#include "B.h"
class A {
 public:
  A() {}
  ~A() {}
  f() {
   auto b = new B(this);
  }
};
Run Code Online (Sandbox Code Playgroud)

在另一个文件中:

#include "A.h"
class B {
 public:
  B(A* a) {}
  ~B() {}
}
Run Code Online (Sandbox Code Playgroud)

但我不明白我得到的编译错误:

B.h: error: ‘A’ has not been declared
A.cpp: error: no matching function for call to ‘B(A&)‘
                                                      *this);
              note: candidate is:
              note: B(int*)
              note: no known conversion for argument 1 from ‘A’ to ‘int*’
Run Code Online (Sandbox Code Playgroud)

为什么我的A类已经转换为int?

son*_*yao 6

这是一个ciucular依赖问题.B.h包括A.h,A.h包括B.h.

实际上,你不需要#include "A.h"in B.h,这里A不需要是完整的类型(即在函数声明中使用它作为参数类型),前向声明就足够了.

class A;  // forward declaration

class B {
 public:
  B(A* a) {}
  ~B() {}
};
Run Code Online (Sandbox Code Playgroud)