繁体   English   中英

std :: function中的类型不完整

[英]Incomplete type in std::function

我有一个类似于以下内容的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出错。

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

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

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);
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM