头文件之间的循环依赖性 [英] cyclic dependency between header files

查看:395
本文介绍了头文件之间的循环依赖性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现一个树状结构有两个类:树和节点。问题是,从每个类,我想调用其他类的函数,所以简单的前向声明是不够的。让我们看一个例子:

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 the other class, so simple forward declarations are not enough. Let's see an example:

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的一个函数。

This is just a simple example to illustrate the problem. So what I want is calling a function of Tree from a Node object.

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

Update #1: Thanks for the answers. I tried to solve the problem like in Java, i.e. using just one file per class. It seems I will have to start separating .cpp and .h files...

更新#2:也粘贴了完整的解决方案。

Update #2: Below, following the hints, I pasted the complete solution too. Thanks, problem solved.

推荐答案

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

In the headers, forward declare the member functions:

class Node
{
    Tree * tree_;
    int id_;

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

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

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.

这篇关于头文件之间的循环依赖性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆