【发布时间】:2021-02-21 16:08:49
【问题描述】:
我有以下头文件(此处为简化说明):
#include <vector>
class Box;
class Item {
int row;
int column;
Box *box;
public:
Item(Box *b) : box(b) {}
void thiswontcompile() { box->dosomething(); }
void foo();
};
class Box {
std::vector<Item*> items;
public:
Box() {}
void addsquare(Item *sq) { items.push_back(sq); }
void bar() { for (int i=0; i<items.size(); i++) items[i]->foo(); }
void dosomething();
};
编译器反对 thiswontcompile() 行,抱怨对不完整类型“class Box”的无效使用。我知道我可以通过将此定义移动到实现文件来纠正错误,但是有没有办法将所有这些编码保留在头文件中?
【问题讨论】:
-
简单地将
thiswontcompile的定义移到Box的定义之后。
标签: c++ header-files circular-reference