我使用模板实现二叉搜索树,并在编译时遇到以下错误。此错误仅在我模板化后出现
Undefined symbols for architecture x86_64:
"bst<int>::insert(int)", referenced from:
_main in main.o
"bst<int>::isFull()", referenced from:
_main in main.o
"bst<int>::bst()", referenced from:
_main in main.o
"bst<int>::~bst()", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [main] Error 1
这是我的主要
#include "bst.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[])
{
bst<int> maple;
maple.insert(5);
maple.insert(10);
maple.insert(3);
maple.insert(4);
maple.insert(15);
maple.insert(9);
maple.insert(2);
}
和我的二分查找树类的一部分
template <class T>
void bst<T>::insert(T d)
{
node *n = new node(d);
if(root == nullptr) root = n;
else
insert_r(n, root);
}
template <class T>
bool bst<T>::insert_r(node* newnode, node* curr)
{
if(curr == nullptr) return false;
if(curr->getData() <= newnode->getData())
{
if(curr->getRight() == nullptr)
{
curr->setRight(newnode);
return true;
}
else
{
return insert_r(newnode, curr->getRight());
}
}
else
{
if(curr->getLeft() == nullptr)
{
curr->setLeft(newnode);
return true;
}
else
{
return insert_r(newnode, curr->getLeft());
}
}
}
和我的节点类
class node
{
public:
node();
node(double d):data{d},right{nullptr},left{nullptr}{};
~node();
node* getRight(){return right;}
node* getLeft(){return left;}
void setRight(node* r){right = r;}
void setLeft(node* l){left = l;}
double getData(){return data;}
void setData(double d){data = d;}
friend std::ostream& operator<<(ostram & out, const node &n);
private:
double data;
node* right;
node* left;
};
和标题bst文件的一部分
template <class T>
class bst
{
public:
bst():root{nullptr}{};
~bst();
void insert(T d);
bool insert_r(node* newnode, node* curr);
void inorder();
void inorder_r(node* n);
void preorder();
void preorder_r(node* n);
void postorder();
void postorder_r(node* n);
T sumAllNodes();
和makefile
all: main
node.o: node.h node.cpp
g++ -c -std=c++0x -g node.cpp
bst.o: bst.h bst.cpp
g++ -c -std=c++0x -g bst.cpp
main.o: main.cpp
g++ -c -std=c++0x -g main.cpp
main: node.o bst.o main.o
g++ -g -std=c++0x node.o bst.o main.o -o main
clean:
rm *.o *~ main