C++模板机制
来源:互联网 发布:微信数据突然没有了 编辑:程序博客网 时间:2024/06/18 07:23
对于执行功能都相同的函数,只是参数类型和返回值类型不同,那么我们可以利用C++的模板机制只需要写一套代码。模板是实现代码重用机制的一种工具,可以大幅度提高程序设计的效率。模板分为函数模板和类模板。
函数模板
函数模板的声明格式如下:
template <class 类型参数>
返回类型 函数名(模板参数表)
{
函数体
}
注意:在template语句和函数模板定义语句之间不能有其它语句。
例如求最大值的模板如下:
#include <iostream>#include <string.h>#include <stdio.h>using namespace std;template <class T>T _max(T x,T y){ return x > y ? x : y;}int main(){ int a = 1; int b = 2; double c = 2.8; double d = 15.4; cout<<_max(a,b)<<" "<<_max(c,d)<<endl; return 0;}
函数模板中允许使用多个类型参数。例如:
#include <iostream>#include <string.h>#include <stdio.h>using namespace std;template <class T1,class T2>void Show(T1 x,T2 y){ cout<<x<<" "<<y<<endl;}int main(){ Show("Lisa","Luce"); Show(18,"Lisa"); return 0;}
类模板
一个类模板允许用户为类定义一种模式,使得类中的某些数据成员,某些成员函数的参数或返回值能取任意数据类型。
类模板的声明格式如下:
template <class T>
class 类名
{
//........
};
在类外定义成员函数时,若此成员函数中有类型参数存在,则需要在函数体外进行模板声明,并且在函数名前的类名后缀加上<T>。例如用类模板实现栈代码如下(STL中stack的源代码也差不多是这样):
#include <iostream>#include <string.h>#include <stdio.h>using namespace std;const int N = 10005;template<class T>class Stack{ private: T S[N]; int size; public: void clear() { size = 0; } void push(T x); T pop(); bool empty();};template<class T>void Stack<T>::push(T x){ if(size == N) return; S[size++] = x;}template<class T>T Stack<T>::pop(){ if(size == 0) return NULL; return S[--size];}template<class T>bool Stack<T>::empty(){ if(size == 0) return true; return false;}int main(){ Stack<int> s; s.clear(); for(int i=1;i<=10;i++) s.push(i); while(!s.empty()) cout<<s.pop()<<endl; return 0;}
1 0
- C的宏定义实现模板函数——C的C++模板函数机制实现
- C++-模板
- C++-模板
- C++:模板
- C++:模板
- C++:模板
- 模板 (C++)
- C ++ 模板
- C ++ 模板
- 【C++】模板
- c++----------模板
- C++--------------------------------------------模板
- c++--模板
- C++:模板
- 模板机制的问题
- discuz模板机制应用
- Tornado模板机制分析
- ecshop模板机制
- 再次写给我们这些浮躁的程序员
- OSGI开发web应用
- 偶遇MySQL/Writing file error (Errcode 28)
- 输出图形
- OpenCV中使用PCA
- C++模板机制
- Android中cordova把加载服务器的JS文件替换成本地JS文件
- 杨震霆(carboy) -传奇人物
- Python 中的类装饰器 类似于JAVA中的annotation
- win8 磁贴
- UVa 11686 Pick up sticks (BFS拓扑排序)
- 解决__bridge NSString *urlstr 内存泄露
- Azkaban添加短信报警功能
- .NET服务器控件编程之ViewState