在另一个 header 的结构中使用结构

Using a struct from one header, within a struct of another

我有一个家庭作业,我需要创建一个二叉树,并在每个节点中指向一个链表。

我的 linkedList 程序在以前的作业中运行。但是在我的二叉树结构中,我想从链表访问该结构。

这是我所说的一个例子。

BinaryTree.h

#ifndef BinaryTree_h
#define BinaryTree_h

#include <iostream>    

using namespace std;    

struct bnode {
    bnode * lChild;
    bnode * rChild;
    string word;

    lnode * lineList; // <--------- This is what I would like to accomplish


};

LinkedList.h

#ifndef LinkedList_h
#define LinkedList_h

#include <iostream>

using namespace std;

struct lnode {
    lnode * prev;
    int data;
    void *pointerData;
    lnode * next;

};

你有两个选择:

  1. #include "LinkedList.h"添加到BinaryTree.h:

    #ifndef BinaryTree_h
    #define BinaryTree_h
    
    #include <iostream>    
    #include "LinkedList.h" // <-- here
    
    struct bnode {
        bnode * lChild;
        bnode * rChild;
        std::string word;
    
        lnode * lineList;
    };
    
    #endif
    
  2. 由于 lineList 成员只是一个指针,您可以(并且应该)向前声明 lnode 类型而不必完全定义它:

    #ifndef BinaryTree_h
    #define BinaryTree_h
    
    #include <iostream>    
    
    struct lnode; // <-- here
    
    struct bnode {
        bnode * lChild;
        bnode * rChild;
        std::string word;
    
        lnode * lineList;
    };
    
    #endif
    

在后一种情况下,您仍然需要在任何需要访问 lineList 成员内容的源文件中使用 #include "LinkedList.h"