c++ - 不能通过这个因为错误的类类型转换

标签 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 了?!

最佳答案

这是一个循环依赖问题。 B.h包含A.hA.h包含B.h

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

class A;  // forward declaration

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

关于c++ - 不能通过这个因为错误的类类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704900/

相关文章:

c++ - 避免在没有原始指针的情况下复制 map 的键

javascript - 如果选中,更改复选框的标签 css 类

javascript - 为什么我必须使用 $(this)?

java - C++等价于Java this

c++ - std::cout 如何知道在哪里打印?

c++ - 除了 std::string 之外,增强 c++ 函数以获取 stringstream

c++ - 如何要求 C++ 模板参数具有某些具有给定签名的方法?

c++ - MFC中如何设置控件在对话框中的初始位置?

c++ - 自定义异常中的损坏消息

c++ - For循环索引类型推导最佳实践