我正在尝试实现一个包含两个类的树状结构:Tree
and 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();
这只是一个简单的例子来说明问题。所以我想要的是调用一个函数Tree
from a Node
object.
更新#1:感谢您的回答。我尝试像 Java 一样解决这个问题,即每个类仅使用一个文件。看来我必须开始分离 .cpp 和 .h 文件......
更新#2:下面,按照提示,我也粘贴了完整的解决方案。谢谢,问题解决了。
在标题中,向前声明成员函数:
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, int id) : tree_(tree), id_(id)
{
tree_->incCnt();
}
Node::~Node()
{
tree_->decCnt();
}
etc
这还具有保持标头可读的效果,因此很容易一目了然地看到类的接口。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)