由于类类型转换错误,因此无法通过

时间:2019-02-15 08:03:15

标签: c++ c++11 this

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

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

在另一个文件中:

#include "A.h"
class B {
 public:
  B(A* a) {}
  ~B() {}
}

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

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*’

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

2 个答案:

答案 0 :(得分:6)

这是一个重大的依赖问题。 B.h包括A.h,而A.h包括B.h

实际上,您不需要#include "A.h"中的B.h,这里A也不需要complete type(即,将其用作参数类型函数声明),forward declaration就足够了。

class A;  // forward declaration

class B {
 public:
  B(A* a) {}
  ~B() {}
};

答案 1 :(得分:3)

您在这里有循环依赖关系。如果class A的定义取决于前者的定义,则class B的定义不能取决于#include的定义。您可以通过将// Don't include the complete definition // #include "A.h" class A; // Instead: forward-declare A class B { public: B(A* a) {} ~B() {} }; 指令之一转换为前向声明来解决此问题。就您而言,

A

尽管如此,您可能仍需要在实现文件中定义#include "A.h"。但这很好,您可以在翻译单元中 select t1.id,t1.parent_id,t1.active from test t1 inner join test t2 on t1.parent_id=t2.id where t1.active <> 'Y' and t2.active='Y'; ,而不会回退到循环依赖问题。

相关问题