相关疑难解决方法(0)

头文件之间的循环依赖

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

我们来看一个例子:

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 */
Run Code Online (Sandbox Code Playgroud)

Node.h:

#ifndef NODE_20100118
#define NODE_20100118

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

class Tree;    // compile error without this …
Run Code Online (Sandbox Code Playgroud)

c++ dependencies header cyclic

9
推荐指数
1
解决办法
6052
查看次数

标签 统计

c++ ×1

cyclic ×1

dependencies ×1

header ×1