【发布时间】:2011-10-10 14:35:05
【问题描述】:
我有两个班级,foo 和 bar。
foo.h #includes bar.h 并包含一个 std::vector 指向 bar 对象的指针。在运行时的某个时刻,bar 必须访问这个指向其他 bar 对象的指针向量。因此,foo 包含一个名为 getBarObjects() 的方法,该方法返回指针数组。
因此,我在 bar.h 中转发声明 foo。我显然还必须转发声明我正在使用的方法 - 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;
}
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;
}
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
}
如果我只是简单地包含其他方式,那么稍后我将在 foo 中遇到同样的问题。有什么建议吗?
【问题讨论】:
标签: c++ circular-dependency forward-declaration