我在ArryList.h里定义了一个类:
template
class arryList
{
public:
arryList(int size = 10):lenth(size){};
arryList(const arryList& L1);
// arryList(int size = 10, int addLen = 2);
~arryList();
private:
T* element;
int lenth; //数组容量
int listsize; //数组存储容量个数
};
然后在ArryList.cpp里实现这个类构造函数。
报错说模板已定义(arrylist.cpp(9): error C2995: 'arryList::arryList(int)' : function template has already been defined),但是把template去掉的话T又会未定义
arryList(int size = 10):lenth(size){};这句话代表你已经定义构造函数为初始化lenth为size的空构造函数了,再在.cpp中定义自然会提示重复。你可以把.h中的这行去掉,然后.cpp中改为
template< class T>
arrayList<T>::arrayList(int size):lenth(size){
this->element = new T[lenth];
listsize = 0;
}
另外希望你下次发代码能发成我这种格式,大家都容易看。
一楼说错了,是吧.h中的那行改为
//原来是
arryList(int size = 10):lenth(size){};
//改为
arryList(int size = 10);
ArryList.h
#ifndef ARRYLIST_H
#define ARRYLIST_H
template<class T>
class arryList
{
public:
arryList(int size = 10){};
arryList(const arryList& L1);
// arryList(int size = 10, int addLen = 2);
~arryList();
private:
T* element;
int lenth; //数组容量
int listsize; //数组存储元素个数
};
#endif // !ARRYLIST_H
ArryList.cpp
#include"ArryList.h"
#include <algorithm>
template<class T>
arryList<T>::arryList(int size)
{
lenth = size;
element = new T[lenth];
listsize = 0;
}
template<class T>
arryList<T>::arryList(const arryList& L1)
{
this->lenth = L1.lenth;
this->listsize = L1.listsize;
this->element = new T[lenth];
copy(L1.element, L1.element + listsize, this->element);
}