C++中模板的使用

来源:互联网 发布:身边有关大数据的例子 编辑:程序博客网 时间:2024/06/11 04:07

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

 

 

原创粉丝点击