Cyclic dependency between header files

后端 未结 4 954
长情又很酷
长情又很酷 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 11:50

    Following the hints, here is the complete solution.

    Tree.h:

    #ifndef TREE_20100118
    #define TREE_20100118
    
    #include "Node.h"
    #include <vector>
    
    class Tree
    {
        int counter_;
        std::vector<Node> nodes_;
    
    public:
    
        Tree();
        void start();
        void incCnt();
        void decCnt();
    };
    
    #endif /* TREE_20100118 */
    

    Tree.cpp:

    #include "Tree.h"
    #include "Node.h"
    
    Tree::Tree() : counter_(0) {}
    
    void Tree::start()
    {
        for (int i=0; i<3; ++i) {
            Node node(this, i);
            this->nodes_.push_back(node);
        }
        nodes_[0].hi();    // calling a function of Node
    }
    
    void Tree::incCnt() {
        ++counter_;
    }
    
    void Tree::decCnt() {
        --counter_;
    }
    

    Node.h:

    #ifndef NODE_20100118
    #define NODE_20100118
    
    class Tree;
    
    class Node
    {
        Tree * tree_;
        int id_;
    
    public:
    
        Node(Tree * tree, int id);
        ~Node();
        void hi();
    };
    
    #endif /* NODE_20100118 */
    

    Node.cpp:

    #include "Node.h"
    #include "Tree.h"
    
    #include <iostream>
    
    Node::Node(Tree * tree, int id) : tree_(tree), id_(id)
    {
        tree_->incCnt();    // calling a function of Tree
    }
    
    Node::~Node() {
        tree_->decCnt();
    }
    
    void Node::hi() {
        std::cout << "hi (" << id_ << ")" << std::endl;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 12:11

    The definition of Tree requires the definition of Node but not the other way around so your forward declaration is correct.

    All that you have to do is removed the definition of any functions that require a full definition of Tree from the Node class body and implement them in a .cpp file where full definitions of both classes are in scope.

    0 讨论(0)
  • 2020-11-29 12:11

    Can you but the constructor/destructor bodies in a .cxx file? You could include Tree.h there.

    0 讨论(0)
提交回复
热议问题