头文件与cpp文件报Link Error
如果我把函数声明和实现都放在头文件中 编译没有问题 代码如下
#ifndef _HashTable_H_
#define _HashTable_H_
template <class E, class K>
class HashTable
{
public:
HashTable(int divisor = 11);
~HashTable(void);
bool Search(E& e, K& k);
bool Insert(E& e);
private:
intD;
bool*empty;
E*ht;
inthSearch(const K& k);
};
template <class E, class K>
HashTable<E, K>::HashTable(int divisor/* = 11*/)
{
D = divisor;
empty = new bool[D];
ht = new E[D];
for(int i=0;i<D;i++)
empty[i] = true;
}
template <class E, class K>
HashTable<E, K>::~HashTable(void)
{
delete [] empty;
empty = NULL;
delete [] ht;
ht = NULL;
}
// 找到空的位置
template <class E, class K>
intHashTable<E, K>::hSearch(const K& k)
{
int i = k%D;
int j = i;
do
{
if(empty[j]||ht[j]==k)
return j;
j = (j+1)%D;
} while (j!=i);
return j;
}
// 查找
template <class E, class K>
bool HashTable<E, K>::Search(E& e, K& k)
{
int b = hSearch(k);
// 如果位置为空或者不等于K 则没找到
if(empty[b]||ht[b]!= k)
return false;
// 否则就找到了
e = ht[b];
return true;
}
// 插入
template <class E, class K>
bool HashTable<E, K>::Insert(E& e)
{
K k = e;
int b = hSearch(k);
// 为空则插入
if(empty[b])
{
ht[b] = e;
empty[b] = false;
return false;
}
else
{
return false;
}
return false;
}
#endif// end _HashTable_H_
#ifndef _HashTable_H_
#define _HashTable_H_
template <class E, class K>
class HashTable
{
public:
HashTable(int divisor = 11);
~HashTable(void);
bool Search(E& e, K& k);
bool Insert(E& e);
private:
intD;
bool*empty;
E*ht;
inthSearch(const K& k);
};
#endif// end _HashTable_H_
#include "StdAfx.h"
#include "HashTable.h"
template <class E, class K>
HashTable<E, K>::HashTable(int divisor/* = 11*/)
{
D = divisor;
empty = new bool[D];
ht = new E[D];
for(int i=0;i<D;i++)
empty[i] = true;
}
template <class E, class K>
HashTable<E, K>::~HashTable(void)
{
delete [] empty;
empty = NULL;
delete [] ht;
ht = NULL;
}
// 找到空的位置
template <class E, class K>
intHashTable<E, K>::hSearch(const K& k)
{
int i = k%D;
int j = i;
do
{
if(empty[j]||ht[j]==k)
return j;
j = (j+1)%D;
} while (j!=i);
return j;
}
// 查找
template <class E, class K>
bool HashTable<E, K>::Search(E& e, K& k)
{
int b = hSearch(k);
// 如果位置为空或者不等于K 则没找到
if(empty[b]||ht[b]!= k)
return false;
// 否则就找到了
e = ht[b];
return true;
}
// 插入
template <class E, class K>
bool HashTable<E, K>::Insert(E& e)
{
K k = e;
int b = hSearch(k);
// 为空则插入
if(empty[b])
{
ht[b] = e;
empty[b] = false;
return false;
}
else
{
return false;
}
return false;
}