c++ - 如何修复 C++ 的不完整类型错误?

标签 c++ incomplete-type

我想使用级别顺序遍历来构建一棵树。当我在私有(private)范围中声明我的队列对象时,我收到错误“字段'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);

};

这是树.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 时实例化队列,编译器需要知道在读取 Tree.hQueue 类是什么样子的。所以你需要添加

#include "Queue.h"

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

关于c++ - 如何修复 C++ 的不完整类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33653420/

相关文章:

c++ - 如何重定向 cout 和 cin?

c++ - GotW #101 "solution"真的能解决什么问题吗?

c++ - C++11 lambda 捕获实际捕获了多少?

c++ - 为什么不能将不完整的类型转换为 void?

c++ - 实现文件将只识别其他类的前向声明

C++ - 循环依赖(在模板化基类中使用子类的内部类型)

c++ - shared_ptr 析构函数、复制和不完整类型

c++ - 在 C++11 中定义只移动对象是否有意义?

c++ - 被 YAML::NodeType::Undefined 与 yaml-cpp 混淆

c++ - 从 vector 中删除空元素