我有两个类,foo
和bar
。
foo.h #include
是bar.h,包含指向bar
对象的指针的std::vector
。在运行时的某个时刻,bar
必须访问指向其他bar
对象的指针向量。因此,foo
包含一个名为getBarObjects()
的方法,该方法返回指针数组。
foo
。显然,我还必须向前声明我使用的方法- foo::getBarObjects()
。由于这返回指向bar
的指针数组,我进入了一个恶性循环。
我不能转发声明Bar,然后简单地转发声明getBarObjects()
,因为这会导致"不允许使用不完整的类型名称"。
foo:
#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
稍后。有什么建议吗?
不能转发声明成员
相反,bar.cpp
应该#include
foo.h
和bar.h
。问题解决了。
通常,如果你使用序列:
- 正向声明所有类类型
- 定义所有类类型
- 类成员主体
一切都会好起来的
您不必包含彼此的foo.h或bar.h,除非您要从另一个头文件访问这两个类的内部。在头文件中根据需要声明类,然后包括源文件中的两个头文件。
foo。
#include <vector>
class bar;
class foo {
public:
foo();
~foo();
std::vector<bar*> getBarObjects();
private:
std::vector<bar*> barObjects;
};
bar.h
class foo;
class bar {
public:
bar(foo *currentFoo);
~bar();
bool dosth();
private:
foo *thisFoo;
}
bar.cpp
#include "foo.h"
#include "bar.h"
bool bar(foo *currentFoo) {
thisFoo = currentFoo;
}
bool bar::dosth() {
thisFoo->getBarObjects();
}
您忘记在foo.h中转发声明向量了。您还可以从getBarObjects
返回vector
的by-value,这可能不是您想要的,并且成员函数的前向声明是无用的。
Also:使用标题保护。与原始指针相比,更倾向于使用适合您情况的智能指针(std::shared_ptr
, unique_ptr
)。注意const
ness