求教,模板源程序文件的编译问题

lincoder666 lincoder666 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我写了个模板SqList,给个大概,看源文件布局即可
//头文件SqList.h :SqList的定义
template<class T> class SqList
{
private:
T *elem; //数据存储地址
int length; //当前长度
int listsize; //当前分配的存储量
int listincrement; //分配增量

public:
SqList(int size=0); //构造函数
~SqList(); //析构函数
void ClearList(); //置为空表

T PrevElem(T cur_e) const;
T NextElem(T cur_e) const;
bool Insert(int pos,T e);
bool Delete(int pos,T& e) ;

} ;

//另一个文件SqList.cpp : SqList的实现
#include "SqList.h"

using namespace std;

template<class T>
SqList<T>::SqList(int size):length(0),listsize(size),listincrement(10)
{
if(!size) cerr<<"size is zero"<<'\n';
elem=new T[size];
if(!elem) exit(1);
}

template<class T>
SqList<T>::~SqList()
{
delete [] elem;
}

template<class T>
inline void SqList<T>::ClearList()
{
delete [] elem;
elem=new T[listsize];
length=0;
}

template<class T>
bool SqList<T>::Insert(int pos,T e)
{
if(pos<1 || pos>length+1) return false;

T* p;
T* q;
if(length>=listsize)
{
listsize+=listincrement;
T* temp=new int[listsize];

q=elem;
p=temp;

for(int i=0;i<length;i++)
{
*p=*q;++p,++q;
}
q=elem;
elem=temp;
delete [] q;
}

q=&(elem[pos-1]);
p=&(elem[length-1]);
while(p>=q) { *(p+1)=*p;--p;}
*(q)=e;
++length;

return true;
}

template<class T>
bool SqList<T>::Delete(int pos,T& e)
{
if(pos<1 || pos>length) return false;
e=elem[pos-1];
for(int i=pos-1;i<length;i++)
{
elem[i]=elem[i+1];
}
--length;
return true;
}

//main.cpp :模板使用

#include <iostream>
#include <stdlib.h>
#include "SqList.h"//顺序表
//#include "SqList.cpp"
using namespace std;

int main(int argc, char *argv[])
{
system("pause");
SqList<int> lt(0);//int链表
lt.Insert(1,12);
lt.Insert(2,13);
system("pause");
return 0;
}

我第一次写模板!
我在Dev-C++编译不过,错误信息
[Linker error] undefined reference to `SqList<int>::SqList(int)'

程序是没问题的,只是不懂的怎么使用模板,组织模板文件?
请问我应该怎么做才正确?

...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
lincoder666
C++ 语言 65,214 成员 250,514 内容