C++中模板的使用

在C++中为了实现代码的重用,我们有继承,重载和多态,重载是通过形参不同来实现,继承是通过子类对象直接使用基类函数来实现,多态是指指向子类对象的基类指针根据对象类型来调用不同的虚函数,而模板是是把类型参数化,更大程度上实现代码的重用。

函数模板:

template<class t>

返回值 函数名(t a)

{

}

实例:

#include <iostream>
using std::cout;
using std::endl;

template <class t>
t max(t a,t b)
{
  return a>b?a:b;
}
int main()
{
 int a=3,b=4;
 cout<<max(a,b)<<endl;
 double d1=3.4,d2=4.5;
 cout<<max(d2,d1)<<endl;
 getchar();

}

类模版:

定义一个类模板:

Template < class或者也可以用typename T >
class类名{
//类定义......
};

说明:其中,template是声明各模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个。

下面示例使用两个栈来模拟一个队列

#include <iostream>
#include <string.h>
#include <fstream>
#include <stack>
#include <exception>
using namespace std;
template <class t>
class NewQueue
{
private:
 stack <t>stack1;
 stack <t>stack2;
public:
 t pop()
 {
  if(stack1.size()>0)
  {
   t temp=stack1.top();
    stack1.pop();
    return temp;
  }else
  {
   if(stack2.size()==0)
   {
    throw new exception("the queue is empty");
   }
   while(stack2.size()>0)
   {
   stack1.push(stack2.top());
   stack2.top();
   }
   t temp=stack1.top();
      stack1.pop();
   return temp;
  }
 
 }
 void push(t val)
 {
  stack1.push(val);
 }
 
};

int main()
{
 NewQueue <int> queue1;
 queue1.push(2);
 cout<<queue1.pop();
 cout<<queue1.pop();
 getchar();
 return 0;
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值