使用类类型的向量进行前向声明——不允许指向不完整类类型的指针
forward declaration with vector of class type - pointer to incomplete class type not allowed
我有两个类,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
相关文章:
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- C++从外部类继承的嵌套类;不允许使用不完整的类型
- E0322:不允许使用抽象类类型 " " 的对象
- 为什么C++不允许两个同名的函数/类模板,区别仅在于非类型模板参数(整型)的类型?
- 不允许将SDL_Cursor与unique_ptr:error不完整类型一起使用
- HTTP POST 请求不允许我定义上下文类型
- 内建数组出现不允许的类型不完整错误
- 为什么 std::array 的演绎指南不允许不同的类型?
- 为什么标准不允许通过引用捕获不完整的异常类型?
- 数组错误(不允许类型不完整)
- 为什么函数返回类型中不允许参数推导?
- std::function 中不允许引用返回类型吗?
- 类中不允许使用不完整的类型,但在类模板中允许使用不完整的类型
- 为什么协程不允许使用占位符返回类型?
- 错误消息:不允许抽象类类型 "X" 的对象:纯虚拟"Y"没有覆盖器
- 错误:不允许使用抽象类类型的对象
- 奇怪的不完整类型不允许错误
- 不完整的类型不允许错误
- c++不完全类型不允许在类内部使用
- 不完全类型不允许出现错误和元组