代码之家  ›  专栏  ›  技术社区  ›  ghborrmann

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

  •  0
  • ghborrmann  · 技术社区  · 4 年前

    我有下面的头文件(这里简化了说明):

    #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();
    };
    

    1 回复  |  直到 4 年前
        1
  •  1
  •   Werner Henze    4 年前

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