我正在尝试用两个类实现一个树状结构: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)