I want to build a tree using level order traversal. When I declare my Queue object in the private scope, I get the error "field 'q' has incomplete type 'Queue'. My program works if I declare a Queue in the addTreeNode(int integer) function, but when I move it to the header file, I get the new error. From what I have read it seems that the Tree class does not know how much memory to allocate to the Queue object. How to I fix this?
EDIT: For anyone browsing this question, the problem has nothing to do with inclusions files etc. The problem here is that Tree has an instance of a Queue, while Queue and Tree are friend classes, meaning they have access to each other's data members. This forces a situation that is circular and wonks out c++. The solution to my problem was to make Queue a template class.
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 Header:
#pragma once
#include "tree.h"
class Queue {
friend class Tree;
private:
typedef struct node {
Tree::treePtr treeNode;
node* next;
}* nodePtr;
nodePtr head;
nodePtr current;
public: //This is where the functions go
Queue();
void push(Tree::treePtr t);
int pop();
void print();
};
This is Tree.h:
#pragma once
class Queue;
class Tree{
friend class Queue;
private:
Queue q;
typedef struct tree {
int data;
tree* left;
tree* right;
}* treePtr;
treePtr root;
int numNodes;
public:
Tree();
void addTreeNode(int integer);
};
This is tree.cpp
#include <cstdlib>
#include <iostream>
#include "Tree.h"
#include "Queue.cpp"
using namespace std;
Tree::Tree() {
root = NULL;
}
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);
q.print();
}