模板函数,模板类

来源:互联网 发布:ubuntu如何安装exe 编辑:程序博客网 时间:2024/04/16 22:58

使用模板函数

#include "stdafx.h"#include "iostream"#include "string"using namespace std;template <typename T>//template <class T> T add(const T &t1,const T &t2){return t1+t2;}int _tmain(int argc, _TCHAR* argv[]){cout<<add(1,2)<<endl;cout<<add(1.1,2.2)<<endl;string x="hello,",y="world";cout<<add(x,y)<<endl;getchar();return 0;}



使用类模板
template <class T,int num>//类型参数表class Stack//Stack类定义{private:T sz[num];//存储空间,用数组表示int point;//指针,表示存储位置(即元素个数)public:Stack();//构造函数bool isEmpty();//判断栈是否为空bool isFull();//判断栈是否已满bool push(const T&);//将一个元素压入栈bool pop(T&);//从栈中弹出一个元素};template<class T,int num>Stack<T,num>::Stack(){point=0;//初始位置为0,栈底}template<class T1,int num1>//参数列表不要求字字相同,但形式要相同bool Stack<T1,num1>::isEmpty(){return point==0;//point为0,说明当前无元素}template<class T,int num>bool Stack<T,num>::isFull(){return point==num;//point为num,说明数组已满}template<class T,int num>bool Stack<T,num>::push(const T& obt){if (isFull())return false;//如果栈已满,压入不成功,返回falseelse{sz[point]=obt;//将传入的元素存储在point指向的当前位置point++;//point加1,向栈顶移动return true;//压入成功,返回true}}template<class T,int num>bool Stack<T,num>::pop(T& obt){if (isEmpty())return false;//如果栈已空,无法弹出,返回falseelse{point--;//point减1,向栈底移动,指向存储的最上面一个元素obt=sz[point];//将point指向的当前位置元素复制给传入参数return true;//弹出成功,返回true}}

#include <iostream>#include "Stack.h"using namespace std;int main(){Stack<int,10> st;//如果是template <class T,int num,int num1> ,则可以这样定义Stack<int ,10 ,12 > st;cout<<"开始时st是否为空? "<<st.isEmpty()<<endl;st.push(5);//压入元素5cout<<"此时st是否为空? "<<st.isEmpty()<<endl;for (int i=1;i<10;i++) {st.push(i);//压入9个元素}cout<<"此时st是否已满?"<<st.isFull()<<endl;int rec=0;while(st.pop(rec))cout<<rec<<"   ";cout<<endl;return 0;}

原创粉丝点击