Aer*_*ius 11 c++ circular-dependency forward-declaration
我有两节课,foo和bar.
foo.h #includes bar.h并包含一个std::vector指向bar对象的指针.在运行时期间的某个时刻,bar必须访问指向其他bar对象的指针向量.因此,foo包含一个getBarObjects()返回指针数组的方法.
因此,我foo在bar.h中转发声明.我显然还要转发声明我正在使用的方法 - foo::getBarObjects().当这返回指针数组时bar,我陷入了恶性循环.
我无法转发声明Bar然后只是转发声明getBarObjects(),因为这导致"不允许不完整的类型名称".
foo.h中:
#include "bar.h"
#include <vector>
class foo {
public:
foo();
~foo();
std::vector<bar*> getBarObjects();
private:
std::vector<bar*> barObjects;
}
Run Code Online (Sandbox Code Playgroud)
bar.h:
class foo;
std::vector<bar*> foo::getBarObjects(); // error, doesn't know bar at this point
class bar {
public:
bar(foo *currentFoo);
~bar();
bool dosth();
private:
foo *thisFoo;
}
Run Code Online (Sandbox Code Playgroud)
bar.cpp:
#include "bar.h"
bool bar(foo *currentFoo) {
thisFoo = currentFoo;
}
bool bar::dosth() {
thisFoo->getBarObjects(); // error, pointer to inomplete class type is not allowed
}
Run Code Online (Sandbox Code Playgroud)
如果我只是简单地包括其他方式,我稍后会遇到同样的问题foo.有什么建议?
Ben*_*igt 20
您无法转发声明成员.
相反,bar.cpp应该#include都foo.h和bar.h.问题解决了.
通常,如果您使用序列:
一切都会好起来的.
除非您从其他头文件访问任一类的内部,否则您不必相互包含foo.h或bar.h.在头文件中根据需要声明类,然后包含源文件中的两个头文件.
foo.h中
#include <vector>
class bar;
class foo {
public:
foo();
~foo();
std::vector<bar*> getBarObjects();
private:
std::vector<bar*> barObjects;
};
Run Code Online (Sandbox Code Playgroud)
bar.h
class foo;
class bar {
public:
bar(foo *currentFoo);
~bar();
bool dosth();
private:
foo *thisFoo;
}
Run Code Online (Sandbox Code Playgroud)
bar.cpp
#include "foo.h"
#include "bar.h"
bool bar(foo *currentFoo) {
thisFoo = currentFoo;
}
bool bar::dosth() {
thisFoo->getBarObjects();
}
Run Code Online (Sandbox Code Playgroud)