と の 2 つのクラスでツリーのような構造を実装しようとしてい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();
これは、問題を説明するための単純な例です。だから私が欲しいのは、オブジェクトTree
から関数を呼び出すことです。Node
更新 #1:回答ありがとうございます。Java のように問題を解決しようとしました。つまり、クラスごとに 1 つのファイルのみを使用しました。.cpp ファイルと .h ファイルの分離を開始する必要があるようです...
更新 #2:以下、ヒントに従って、完全なソリューションも貼り付けました。ありがとう、問題は解決しました。