std::函数中的类型不完整

Incomplete type in std::function

本文关键字:类型 函数 std      更新时间:2023-10-16

我有一个类似于以下内容的Target类:

class Target
{
  std::function<void(A&,B&,C&)> Function;
}

现在,其中一个参数类型(比如A)有一个Target成员,并试图调用它的函数:

class A
{
  Target target;
  void Foo(B& b, C& c)
  {
    target.Function(*this,b,c);
  }
}

在后面的某个地方,这两种类型出现在头文件中。考虑到循环依赖关系,有一个正向声明,不幸的是,还有一个error : pointer to incomplete class type is not allowed错误。

所以问题是,我该怎么办?

您有一个循环依赖性问题。将target声明为class A中的指针,并在构造函数中适当地分配它,并在类的析构函数中取消分配它:

class A
{
  A() : target(new Target) {}
  ~A() { delete target; }
  Target *target;
  void Foo(B &b, C &c)
  {
    target->Function(*this, b, c);
  }
};

如果您的编译器支持C++11,请改用智能指针:

class A
{
  A() : target(std::unique_ptr<Target>(new Target)) {}
  std::unique_ptr<Target> target;
  void Foo(B &b, C &c)
  {
    (*target).Function(*this, b, c);
  }
};