beg*_*neR 2 c++ forward-declaration
我使用以下简单文件重现错误.
它说:
字段有不完整类型'Foo'
bar.h:
class Foo;
class Bar{
private:
int x_;
Foo foo_; // error: incomplete type
public:
void setx(int x) {x_ = x;};
void increment(int);
};
class Foo{
public:
void run(int y,Bar& bar) {bar.setx(y);};
};
void Bar::increment(int i){foo_.run(i,*this);}
Run Code Online (Sandbox Code Playgroud)
成员foo_不能是引用或指针.原因是在我的实际代码中,我无法在Bar的初始化列表中初始化Foo.
你的问题可以减少到这个:
class Foo;
class Bar{
Foo foo_; // error: incomplete type
};
Run Code Online (Sandbox Code Playgroud)
在这里你做了一个类型的前向声明Foo,即一个没有完整定义的声明:在C++中声明指针是足够的,但不是你所做的具体实例Bar.
要么为您的班级提供完整的定义:
class Foo{
// put details here
};
class Bar{
Foo foo_; // OK
};
Run Code Online (Sandbox Code Playgroud)
或者使用(智能)指针,例如:
class Foo;
class Bar{
std::unique_ptr<Foo> foo_; // OK
};
Run Code Online (Sandbox Code Playgroud)
或者改变Bartek Banachewicz指出的订单声明.
在这种情况下,它很简单:因为Foo只使用对 的引用Bar,翻转它们就可以了:
class Bar;
class Foo{
public:
void run(int y,Bar& bar);
};
class Bar { ... };
void Foo::run(int y, Bar& bar) {
bar.setx(y);
}
Run Code Online (Sandbox Code Playgroud)
您还需要移动Foo::run下面的主体,因为它实际上是在使用Bar成员函数。