C++模板:模板类

本文探讨了C++中类定义的方式及其局限性,并介绍了如何使用类模板来实现更通用的类设计。通过一个具体实例,展示了如何通过模板参数将类的类型从特定类型(如int)抽象化为任意类型(ItemType),从而生成不同类型的list对象。文中还提供了一个Glist类模板的例子,说明如何在实例化时传入不同类型的参数来创建不同用途的list容器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们常见的类定义方式

class List

{

private:

int list[10];

int len;

public:

.......

};

这种方式有一个缺点就是只能用来实例化int类型的list,要使一个类成为真正的模板,需要一种语言构造,它把int抽象化成ItemType成为一个参数,通过C++的类模板可以实现这一功能。

 

template <模板形参列表>

模板形参包括:classtypename

 

template <class ItemType>

class List

{

private:

ItemType list[10];

ItemType len;

public:

.......

};

在实例化的时候我们可以通过传入不同类型(intfloat等)来生成不同类型的list对象。

附上写的小栗子:

glist.h

const int MAX_LEN=100;

template<class ItemType>

 

class Glist

{

   private:

      int length;

      int currentpos;

      ItemType list[MAX_LEN];

   public:

      Glist()

      {

         length=0;

         currentpos=0;

      }

      void insert(const ItemType & item)

      {

          if(length>=MAX_LEN)

          {

              return;

          }

         list[++length]=item;

      }

      int getLength()

      {

         return length;

      }

      bool isEmpty()

      {

          return (length==0);

      }

      bool isFull()

      {

          return (length==MAX_LEN);

      }

      void deleteItem(const ItemType & item)

      {

          int index=0;

          while(index<length && list[index]!=item)

          {

              index++;

          }

          if(index<length)

          {

              list[index]=list[length-1];

          }

          length--;

      }

      int indexOf(const ItemType & item)

      {

          int index=0;

          while(index<length && list[index]!=item)

          {

              index++;

          }

          return (index<length)?index:-1;

      }

      ItemType getValueByIndex(int index)

      {

          return list[index];

      }

};

 

testList.cpp

#include <iostream>

#include "glist.h"

using namespace std;

int main()

{

   Glist<int> intList;

   Glist<char> charList;

   intList.insert(3);

   intList.insert(5);

   charList.insert('s');

   charList.insert('c');

   cout<<"int list len"<<intList.getLength()<<endl;

    cout<<"char list len:"<<charList.getLength()<<endl;

   return 0;

}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值