c – 头文件之间的循环依赖性

我正在尝试使用两个类实现树状结构:树和节点.问题是,从每个类我想调用另一个类的函数,所以简单的前向声明是不够的.

我们来看一个例子:

tree.h中:

#ifndef TREE_20100118
#define TREE_20100118

#include <vector>
#include "Node.h"

class Tree
{
    int counter_;
    std::vector<Node> nodes_;

public:

    Tree() : counter_(0) {}

    void 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 incCnt() {
        ++counter_;
    }

    void decCnt() {
        --counter_;
    }

};

#endif /* TREE_20100118 */

Node.h:

#ifndef NODE_20100118
#define NODE_20100118

#include <iostream>
//#include "Tree.h"

class Tree;    // compile error without this

class Node
{
    Tree * tree_;
    int id_;

public:

    Node(Tree * tree,int id) : tree_(tree),id_(id)
    {
//      tree_->incCnt();    // trying to call a function of Tree
    }

    ~Node() {
//      tree_->decCnt();    // problem here and in the constructor
    }

    void hi() {
        std::cout << "hi (" << id_ << ")" << endl;
    }

};

#endif /* NODE_20100118 */

呼叫树:

#include "Tree.h"
...
Tree t;
t.start();

这只是一个简单的例子来说明问题.所以我想要的是从Node对象调用Tree的函数.

更新#1:感谢您的回答.我尝试像在Java中一样解决问题,即每个类只使用一个文件.看来我必须开始分离.cpp和.h文件……

更新#2:下面,根据提示,我也粘贴了完整的解决方案.谢谢,问题解决了.

解决方法

在标题中,forward声明成员函数:

class Node
{
    Tree * tree_;
    int id_;

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

在包含所有必需标头的单独.cpp文件中,定义它们:

#include "Tree.h"
#include "Node.h"

Node::Node(Tree * tree,id_(id)
{
  tree_->incCnt();
}

Node::~Node() 
{
  tree_->decCnt();
}

etc

这也可以保持标题的可读性,因此很容易看到类的界面一目了然.

相关文章

文章浏览阅读315次。之前用C语言编过链表,这几天突然想用C+...
文章浏览阅读219次。碰到问题就要记录下来,防止遗忘吧。文章...
文章浏览阅读1.8k次,点赞11次,收藏37次。因为自己对决策树...
文章浏览阅读492次。C++ 设计模式之策略模式
文章浏览阅读683次。我也算是个C++的小白,对于C++中的谓语我...
文章浏览阅读225次。又看了一遍操作符的东西,感觉之前对操作...