如何解析头文件中的循环引用

问题描述

我有以下头文件(为了说明而简化):

#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的定义移动到头文件的末尾,您只需要让函数inline即可。

#include <vector>
class Box;
class Item {
  int row;
  int column;
  Box *box;
public:
  Item(Box *b) : box(b) {}
  void thiswontcompile();
  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();
};

inline void Item::thiswontcompile() { box->dosomething(); }