liuxin95 2018-09-20 14:16 采纳率: 0%
浏览 1069
已采纳

类模板分开定义时,.cpp文件实现构造函数,报错模板已定义

我在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又会未定义

  • 写回答

3条回答 默认 最新

  • JonathanYan 2018-09-20 15:15
    关注

    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;
     }
    

    另外希望你下次发代码能发成我这种格式,大家都容易看。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?