我有一个类似于下面的 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);
}
}
在某处,这两种类型出现在头文件中。鉴于循环依赖,有一个前向声明,不幸的是,一个错误:不允许指向不完整类类型的指针
错误。
所以问题是 - 我该怎么办?
最佳答案
你有一个 circular dependency问题。将 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);
}
};
关于c++ - std::function 中的不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035586/