【问题标题】:How to Resolve Circular Reference in Header File如何解决头文件中的循环引用
【发布时间】: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


【解决方案1】:

你可以将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(); }

【讨论】:

    猜你喜欢
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多