模板类

模板类,实现一个简单的单链表

#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename type>
class List;

template <typename type>
class note//此后这个类的类型就是 note<type> 以后有用到类型必须加<type>
{
friend class List<type>;
private:
    type a;//type类型的变量,
    note<type> * next;
public:
    note()
    {
        a=type();//type类型对应的零初始化,如果type是int .则a=int();即a=0;如果是double,则a=double();即a=0.0000000000;
        next=NULL;
    }
    note(type b,note<type> *n=NULL)
    {
        a=b;
        next=n;
    }
};

template <typename type>
class List
{
private:
    note<type> * frist;
    note<type> * last;
    int n;
public://模板类内的函数必须是模板函数
    List()
    {
        last=frist=(note<type>*)malloc(sizeof(note<type>));
        n=0;
    }
    void Push_back(type timp);
    void showlist()const
    {
        note<type> *p=frist->next;
        while(p)
        {
            cout<<p->a<<endl;
            p=p->next;
        }
    }
};
template <typename type>//模板类的函数都是模板函数,如果要在类外定义一定不要忘了写函数模板
void List<type>::Push_back(type timp)//作用域限定一定是List<type>类型;
{
    note<type> *p=(note<type>*)malloc(sizeof(note<type>));
    p->a=timp;
    p->next=NULL;
    last->next=p;
    last=last->next;
    n++;
}
//类模板的类声明和具体的函数体不能像替他类一样分开在不同文件里,链接会有问题.除非有其他操作?
int main()
{
    List<int> a;
    for(int i=0;i<10;i++)
    {
        a.Push_back(i);
    }
    cout << "Hello world!" << endl;
    a.showlist();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值