template 不能分别在.h和.cpp中定义模板

时间:2023-03-09 07:43:29
template 不能分别在.h和.cpp中定义模板

先上代码:

 #ifndef SEQLIST_H
#define SEQLIST_H #include <iostream> const int MaxLength = ; template <typename type>
class SeqList
{
public:
SeqList();
~SeqList();
int getLength() const;
type getElement(int i) const;
int locate(type &item) const;
int insert(const type item,int i);
type deleteElement(const int i);
bool isEmpty() const;
void clear();
int append(type item);
private:
type data;
int length;
}; #endif // SEQLIST_H

以上是数据结构中定义的顺序线性表的头文件,接下来的是类的实现过程,我是直接用的Qt做的,比较省事嘛。

 #include "seqlist.h"

 using namespace  std;

 //构造函数
template <typename type> SeqList<type>::SeqList():length()
{
data = new type[MaxLength];
} //析构函数
template <typename type> SeqList<type>::~SeqList()
{
delete []data;
return length;
} //得到链表当前长度
template <typename type> int SeqList<type>::getLength() const
{
return length;
} //根据索引得到相应元素
template <typename type> type SeqList<type>::getElement(int i) const
{
if(i>=&&i<length)
return data[i];
return NULL;
} //根据元素得到索引位置
template <typename type> int SeqList<type>::locate(type &item) const
{
for(int i = ;i<length;i++)
{
if(data[i]==item)
return i;
else
{
break;
}
}
} //在第i个元素之前插入元素item
template <typename type> int SeqList<type>::insert(const type item, int i)
{
if(length == MaxLength)
return ;
if(i<||i>length)
return ;
for(int j = length;j>i;j--)
{
data[j]= data[j-];
}
data[i] = item;
length++;
return ;
} //删除第i个元素
template <typename type> type SeqList<type>::deleteElement(const int i)
{
if(length == )
return ;
if(i<||i>length)
return ;
type t = data[i];
for(int j = i;j<length;j++)
{
data[j] = data[j+];
}
length --;
return t;
} //查询链表是否为空
template <typename type> bool SeqList<type>::isEmpty() const
{
if(length == )
{
return true;
}
return false;
} //清空链表
template <typename type> void SeqList<type>::clear()
{
length =;
} //添加一个元素
template <typename type>int SeqList<type>::append(type item)
{
if(length == MaxLength)
return ;
data[length] = item;
return ;
}

代码中如果存在错误,就是我才学数据结构,自己在实验室做练习时写错了。毕竟才学。

然后是main.cpp

 #include "seqlist.h"
#include <iostream> using namespace std; int main()
{
SeqList<int> *list = new SeqList<int>;
for(int i = ;i<;i++)
{
list->insert(i,i);
} for(int i = ;i<;i++)
{
list->getElement(i);
}
list->append();
return ;
}

然后事情就发生了,我使用Qt已经有一段时间了,对Qt来说不说炉火纯青,但也了解不少了,怎么出现这种情况了呢?

error: LNK2019: 无法解析的外部符号 "public: int __thiscall SeqList<int>::append(int)" (?append@?$SeqList@H@@QAEHH@Z),该符号在函数 _main 中被引用

error: LNK2019: 无法解析的外部符号 "public: __thiscall SeqList<int>::SeqList<int>(void)" (??0?$SeqList@H@@QAE@XZ),该符号在函数 _main 中被引用

赚到VS上还是不行,想了会想起来应该是类中定义的方法未实现,于是把.cpp中的方法全部复制到了.h中,删掉.cpp。OK了

原来template 定义模板是不能分别在.h和.cpp中写的。