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;
}
- C++set模板的使用
- vs2005中模板的使用
- SharePoint2007中模板的使用
- SharePoint2007中模板的使用
- C++中模板的使用
- C++中模板的使用
- cuda中模板的使用
- CUDA中模板的使用
- C++中模板的使用
- C++中模板的使用
- C++_类模板的使用
- C++List模板类的使用
- C++template(模板)的使用
- C++-使用模板解决问题
- flask模板中使用 jaavscript接收模板传递的值
- atl中常见的模板使用手法
- atl中常见的模板使用手法
- c++中模板类的使用详解
- 14周心得
- 自我介绍
- Linux 64位下栈布局
- HDU4574/2013年长沙赛区Bombs
- [反思]2013-06-02手机被偷
- C++中模板的使用
- makefile使用通配符的一个例子
- js正则表达式验证各类需求(整数,实数,小数,时间,URL等)
- flash下载网络图片
- MSRA我来了
- 14-1 没名字
- 堆排序 (建立大顶堆)
- 有趣的发现,引用初始化为整数
- Sicily 1252 Defining Moment (SOJ 1252) 【暴力匹配】