【发布时间】:2011-01-06 12:56:33
【问题描述】:
我正在尝试实现具有两个类的树状结构: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 */
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: 在下面,按照提示,我也粘贴了完整的解决方案。谢谢,问题解决了。
【问题讨论】:
标签: c++ header cyclic-dependency