【问题标题】:How to fix incomplete type error c++? [duplicate]如何修复不完整的类型错误 C++? [复制]
【发布时间】:2016-02-12 17:07:30
【问题描述】:

我想使用级别顺序遍历构建一棵树。当我在私有范围内声明我的队列对象时,我收到错误“字段'q'的类型'队列'不完整。如果我在 addTreeNode(int integer) 函数中声明一个队列,我的程序可以工作,但是当我将它移动到头文件,我得到了新的错误。从我读过的内容来看,Tree 类似乎不知道要为 Queue 对象分配多少内存。我该如何解决这个问题?

编辑:对于浏览此问题的任何人,问题与包含文件等无关。这里的问题是 Tree 有一个 Queue 的实例,而 Queue 和 Tree 是朋友类,这意味着它们可以访问彼此的数据成员。这迫使一种情况是循环的,并且会影响 c++。我的问题的解决方案是使 Queue 成为模板类。

这里是主类:

#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();

};

这是 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);

};

这是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();

}

【问题讨论】:

  • 不幸的是,前向声明仅适用于指针和引用。和功能。
  • 对于浏览此问题的任何人,问题与包含文件等无关。因此,如果您的问题与我的问题相同,单击上面的重复答案将无济于事。这里的问题是 Tree 有一个 Queue 的实例,而 Queue 和 Tree 是友元类,这意味着它们可以访问彼此的数据成员。这迫使一种情况是循环的,并且会影响 c++。我的问题的解决方案是使 Queue 成为模板类。

标签: c++ incomplete-type


【解决方案1】:

要在创建Tree 时实例化您的队列,编译器需要知道Queue 类在读取Tree.h 时的样子。所以你需要添加

#include "Queue.h"

Tree.h,这将使编译器在开始读取Tree之前看到完整的Queue声明。

【讨论】:

  • 我试过这个,但这会引入各种错误。我在“tree.cpp”中#include“Queue.cpp”,如果我在tree.cpp中声明队列,一切正常
  • 从不(嗯,几乎从不)#include .cpp 文件,只是头文件。
  • 我从我的程序中添加了其他 .h 和 .cpp 文件。如果我尝试在 Tree.h 中包含 Queue.h 文件,就像我说的那样,会有很多错误。我试图更改哪些文件包含哪些内容,但这似乎在这里不起作用。
  • 您现在有一个循环引用:Queue.h 包含 Tree.h,Tree.h 包含 Queue.h。其中一个应该是前向声明(Queue.h 中的class Tree;),另一个应该是包含。
  • 当我按照你说的做时,Queue.h 无法识别结构节点中treePtr 的类型*
猜你喜欢
  • 2017-01-08
  • 2021-12-09
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多