首页 文章

'struct Node'的无效使用/转发声明

提问于
浏览
1

对于一个学校项目,我试图创建一个二叉搜索树,同时我们应该学习如何在课堂上使用“友谊” . 我在编译时得到的错误是:[为了清晰起见,我在代码中放置了错误来源的错误]

$ make -f makefile.txt
g++ -Wall -W -Werror -pedantic -g -c BST.cpp
BST.cpp: In member function `void BST::insert(std::string, std::string)':
BST.cpp:13: error: invalid use of undefined type `struct Node'
BST.h:19: error: forward declaration of `struct Node'
makefile.txt:9: recipe for target `BST.o' failed
make: *** [BST.o] Error 1

基本上我希望能够访问Node类,就好像该类是嵌套的一样(但是为了这个编程赋值,我不允许嵌套它) . 显然,简单地使用'ptr-> m_data'是行不通的,但是我能做些什么来使它工作呢?

Node.h

#ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED

#include <iostream>
#include <string>

using namespace std;

class BST;
class Node
{
public:
    Node(string key, string data)
    {n_key = key; n_data = data;}
    ~Node();
private:
    string m_key;
    string m_data;
    Node *m_left;
    Node *m_right;
    //Node *m_parent;
};


#endif // NODE_H_INCLUDED

BST.h

#ifndef BST_H_INCLUDED
#define BST_H_INCLUDED

#include <iostream>
#include <string>

using namespace std;

class BST
{
public:
    BST()
    {m_root = NULL;}
    ~BST();
    void insert(string key, string data);
    void find(string key);
    void remove(string key, string data);
    void print();
    friend class Node; //Error: forward declaration of 'struct Node'
private:
    Node* m_root;

};

#endif // BST_H_INCLUDED

为什么当我调用下面的代码行时,它会读出上面的错误消息? (注意:以下代码来自BST.cpp)

#include "BST.h"

void BST::insert(string key, string data)
{
    Node* yPtr = NULL;
    Node* xPtr = m_root;
    while(xPtr != NULL)
    {
        yPtr = xPtr;
        if(key < xPtr->m_key) //Error: invalid use of undefined type 'struct Node'
        {

        }
    }
}

1 回答

  • 2

    当编译器到达BST.cpp中的那一行时,编译器还没有看到 Node 的定义 . 请注意,这是编译器需要查看Node结构的第一行 . 你需要在BST.cpp中 #include "Node.h" .

相关问题