I have been struggling with errors when trying to build a binary tree using a queue. The problem is what classes should include what files and how to reference objects from the other classes? I threw my files into an IDE in an attempt to pinpoint just what the problems are and the results are below. Currently my issue is that in the Queue.h file, treePtr "does not name a type". You can see the evolution of this problem here This question is different from other posts because the two classes are friend classes. This brings up the problem of circular dependencies. I have tried all sorts of combinations of including files and forward declaring but one combination causes one type of issue, and another creates different errors.
Here is the main class:
#include <cstdlib>
#include "Tree.cpp"
using namespace std;
int main() {
Tree tree;
tree.addTreeNode(5);
return 0;
}
Here is the Queue.h:
#ifndef QUEUE_H_
#define QUEUE_H_
class Tree; //Was instructed to put this here
class Queue {
friend class Tree;
private:
typedef struct node {
Tree::treePtr treeNode; //Here is the problem
node* next;
}* nodePtr;
nodePtr head;
nodePtr current;
public:
Queue();
virtual ~Queue();
void push(Tree::treePtr t); //Here is the problem
int pop();
void print();
};
#endif /* QUEUE_H_ */
This is Tree.h:
#ifndef TREE_H_
#define TREE_H_
#include "Queue.h" //Was instructed to put this here
class Tree {
friend class Queue;
private:
Queue q; //Edit: Most likely problem since Queue and Tree are friends
typedef struct tree {
int data;
tree* left;
tree* right;
}* treePtr;
treePtr root;
int numNodes;
public:
Tree();
virtual ~Tree();
void addTreeNode(int integer);
};
#endif /* TREE_H_ */
This is tree.cpp
#include <cstdlib>
#include <iostream>
#include "Tree.h"
using namespace std;
Tree::Tree() {
root = NULL;
numNodes = 0;
}
void Tree::addTreeNode(int integer) {
numNodes++;
treePtr t = new tree;
t->left = NULL;
t->right = NULL;
t->data = integer;
cout << "add root\n";
root = t;
q.push(t); //This is a problem
q.print();
}
Tree::~Tree() {
// TODO Auto-generated destructor stub
}