Cyclic dependency between header files

后端 未结 4 966
长情又很酷
长情又很酷 2020-11-29 11:45

I\'m trying to implement a tree-like structure with two classes: Tree and Node. The problem is that from each class I want to call a function of th

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 12:09

    In the headers, forward declare the member functions:

    class Node
    {
        Tree * tree_;
        int id_;
    
    public:
        Node(Tree * tree, int id);
        ~Node();
        void hi();
    };
    

    In a separate .cpp file that includes all the required headers, define them:

    #include "Tree.h"
    #include "Node.h"
    
    Node::Node(Tree * tree, int id) : tree_(tree), id_(id)
    {
      tree_->incCnt();
    }
    
    Node::~Node() 
    {
      tree_->decCnt();
    }
    
    etc
    

    This also has the effect of keeping your headers readable, so it is easy to see a class's interface at a glance.

提交回复
热议问题