如何修复不完全类型错误c ++? [英] How to fix incomplete type error c++?
问题描述
我想使用级别顺序遍历构建树。当我声明我的Queue对象在私有作用域,我得到错误字段'q'有不完全类型'队列'我的程序工作,如果我在addTreeNode(int integer)函数声明一个队列,但是当我移动它头文件,我得到新的错误从我已经读了似乎Tree类不知道多少内存分配给Queue对象如何解决这个?
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?
编辑:对于浏览这个问题的任何人,这个问题与包含文件等无关。这里的问题是Tree有一个队列的实例,而Queue和Tree是朋友类,这意味着他们可以访问对我的问题的解决方案是让Queue成为一个模板类。
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.
这里是主类:
#include <cstdlib>
#include "Tree.cpp"
using namespace std;
int main() {
Tree tree;
tree.addTreeNode(5);
return 0;
}
以下是队列标题:
#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();
};
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);
};
这是tree.cpp
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();
}
推荐答案
您的队列创建树
时,编译器需要知道 Queue
类看起来像什么样当 Tree.h
。因此您需要添加
To instantiate your queue upon creation of the Tree
, the compiler needs to know what the Queue
class looks like when reading Tree.h
. So you need to add
#include "Queue.h"
到 Tree.h
,这将使整个 Queue
声明在开始阅读 Tree
之前由编译器可见。
to Tree.h
which will make the full Queue
declaration visible to the compiler before it starts reading Tree
.
这篇关于如何修复不完全类型错误c ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!