C++模板类使用(创建链表)

C++语言 码拜 7年前 (2017-04-22) 1425次浏览
首先说一下,本人要做一个简单的链表,然后用到了模板类,但是在编译的时候报错,原因是匹配不到函数,具体代码如下,还有其他的函数也是相同的问题。
拜托各位路过的高手提点一下。
头文件SLList.h

#ifndef SLLIST_H_INCLUDED
#define SLLIST_H_INCLUDED
#include <iostream>
using namespace std;
template<class T>
struct SLNode
{
    T data;
    SLNode<T> *next;
    SLNode(SLNode * nextNode=NULL){next=nextNode;}
    SLNode(const T& item,SLNode *nextNode=NULL)
    {
        data=item;next=nextNode;
    }
};
template<class T>
class SLList
{
private:
    SLNode<T> *head;
    SLNode<T> *tail;
    SLNode<T> *currptr;
    int size;
public:
    SLList();
    SLIist(T& item);
    ~SLList();
    bool IsEmpty(void)const{return head->next==NULL;}
};
#endif // SLLIST_H_INCLUDED

SLList.cpp

#include "SLList.h"
template<class T>
SLList<T>::SLList()
{
    head=tail=currptr=new SLNode<T>();
    size=0;
}
template<class T>
SLList<T>::SLList(T& item)
{
    tail=currptr=new SLNode<T>(item);
    head=new SLNode<T>(currptr);
    size=1;
}
template<class T>
SLList<T>::~SLList()
{
    while(!IsEmpty())
    {
        currptr=head->next;
        head->next=currptr->next;
        delete currptr;
    }
    delete head;
}

main.cpp

#include <iostream>
using namespace std;
#include "SLList.h"
int main()
{
    SLList<int> sl(1);
}

这个问题解决了,本人想其他的函数也应该是一样的近似解决。

解决方案

15

SLList.cpp 里除了 #include 行其它复制到 SLList.h 文件里,然后把 cpp 删掉。
当你开始使用模板时,就不要想着声明与定义分离了。

50

模板不支持分离编译,把声明和实现放到同一个文件里
原因参看:http://www.2cto.com/kf/201404/294104.html

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C++模板类使用(创建链表)
喜欢 (1)
[1034331897@qq.com]
分享 (0)