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
基本上我希望能够访问节点类好像类是嵌套(我不是但是为了这个编程任务,允许将它嵌套)。显然,仅仅使用'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'
{
}
}
}
那么,你的'Node.h'包含在哪里?我没有看到它的任何地方。 – AnT
在Node.cpp文件中(该文件虽然完全是空的) – user3040019
这不起作用。 'BST.cpp'不知道关于你的'Node.cpp'的任何信息。如果你想在'BST.cpp'中使用'Node'的内部,你必须在'BST.cpp'中包含'Node.h'。没有它,你的'Node'在'BST.cpp'中保持未定义。 – AnT