Cyclic dependency between header files

后端 未结 4 958
长情又很酷
长情又很酷 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条回答
  •  萌比男神i
    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 
    
    class Tree
    {
        int counter_;
        std::vector 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 
    
    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;
    }
    

提交回复
热议问题