我正在尝试在单独的文件中创建BST类,但出现链接器命令失败。我已经检查了很多次,但是找不到错误。这是代码。
BST.h
#ifndef BST_H
#define BST_H
#include <iostream>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
class BST
{
private:
node *root;
public:
BST();
void Insert(int);
bool Search(int);
bool Delete(int);
void Display();
};
#endif
BST.cpp
#include "BST.h"
BST::BST()
{
root = NULL;
}
void InsertNode(node *&, int);
void BST::Insert(int val)
{
InsertNode(root, val);
}
bool SearchNode(node *&, int);
bool BST::Search(int val)
{
return SearchNode(root, val);
}
bool DeleteNode(node *&, int);
bool BST::Delete(int val)
{
return DeleteNode(root, val);
}
void InOrderTraversalDisplay(node *&);
void BST::Display()
{
InOrderTraversalDisplay(root);
}
void InsertNode(node *&ptr, int val)
{
if (ptr == NULL)
{
ptr = new node;
ptr->data = val;
ptr->left = NULL;
ptr->right = NULL;
}
else if (val > ptr->data)
{
InsertNode(ptr->right, val);
}
else if (val <= ptr->data)
{
InsertNode(ptr->left, val);
}
}
void InOrderTraversalDisplay(node *&ptr)
{
if (ptr == NULL)
{
cout << "tree is empty" << endl;
}
if (ptr->left != NULL)
{
InOrderTraversalDisplay(ptr->left);
}
cout << ptr->data << endl;
if (ptr->right != NULL)
{
InOrderTraversalDisplay(ptr->right);
}
}
bool SearchNode(node *&ptr, int val)
{
if (ptr == NULL)
{
return false;
}
else if (ptr->data == val)
{
return true;
}
else
{
if (val > ptr->data)
{
return SearchNode(ptr->right, val);
}
else if (val < ptr->data)
{
return SearchNode(ptr->left, val);
}
}
return false;
}
int Getsuccessor(node *ptr)
{
ptr = ptr->right;
while (ptr->left != NULL)
{
ptr = ptr->left;
}
return ptr->data;
}
int Getsuccessor(node *);
bool DeleteNode(node *&ptr, int val)
{
if (ptr == NULL)
{
return false;
}
else if (val < ptr->data)
{
return DeleteNode(ptr->left, val);
}
else if (val > ptr->data)
{
return DeleteNode(ptr->right, val);
}
else
{
if (ptr->left == NULL && ptr->right == NULL)
{
delete ptr;
ptr = NULL;
return true;
}
else if (ptr->left != NULL && ptr->right == NULL)
{
node *temp = ptr;
ptr = ptr->left;
delete temp;
return true;
}
else if (ptr->left == NULL && ptr->right != NULL)
{
node *temp = ptr;
ptr = ptr->right;
delete temp;
return true;
}
else
{
int succ;
succ = Getsuccessor(ptr);
ptr->data = succ;
return DeleteNode(ptr->right, succ);
}
}
}
main.cpp
#include <iostream>
#include "BST.h"
using namespace std;
int main()
{
BST b;
b.Insert(5);
b.Insert(4);
b.Delete(4);
b.Delete(14);
b.Display();
return 0;
}
出现以下错误。
Undefined symbols for architecture x86_64:
"BST::Delete(int)", referenced from:
_main in main-4bcc78.o
"BST::Insert(int)", referenced from:
_main in main-4bcc78.o
"BST::Display()", referenced from:
_main in main-4bcc78.o
"BST::BST()", referenced from:
_main in main-4bcc78.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)