트리와 노드의 두 클래스로 트리 구조를 구현하려고합니다. 문제는 각 클래스에서 다른 클래스의 함수를 호출하기를 원하기 때문에 간단한 전달 선언으로는 충분하지 않다는 것입니다.헤더 파일 간의 주기적 종속성
#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.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의 예로 들어 보자 이것은 문제를 설명하기위한 간단한 예일뿐입니다. 그래서 내가 원하는 것은 Node 객체로부터 Tree의 함수를 호출하는 것이다.
업데이트 # 1 : 답변 해 주셔서 감사합니다. Java와 같은 문제를 해결하려고했습니다. 즉 클래스 당 하나의 파일 만 사용했습니다. .cpp 파일과 .h 파일을 분리해야 할 것 같습니다 ...
업데이트 # 2 : 아래의 힌트 다음에 완전한 솔루션도 붙여 넣습니다. 고마워, 문제 해결. 헤더에서