本文主要是介绍类模板非类型形参实现Stack,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原创地址:http://www.cnblogs.com/gw811/archive/2012/10/25/2738929.html
TemplateDemo.h
#include <iostream>
using namespace std;
#ifndef TEMPLATE_DEMO_HXX
#define TEMPLATE_DEMO_HXXtemplate<class T,int MAXSIZE> class Stack{
private:T elems[MAXSIZE];int numElems;
public:Stack();void push(T const&);void pop();T top() const;bool empty() const{return numElems == 0;}bool full() const{return numElems == MAXSIZE;}};template<class T,int MAXSIZE>
Stack<T,MAXSIZE>::Stack():numElems(0){}template<class T,int MAXSIZE>
void Stack<T,MAXSIZE>::push(T const& elem){if(numElems == MAXSIZE){cout << "stack is pull" << endl;}elems[numElems++] = elem;
}template<class T,int MAXSIZE>
void Stack<T,MAXSIZE>::pop(){if(numElems <= 0){cout << "stack is empty" << endl;}--numElems;
}template<class T,int MAXSIZE>
T Stack<T,MAXSIZE>::top() const{if(numElems <= 0){cout << "stack is empty" << endl;}return elems[numElems-1];
}#endif // TEMPLATH_DEMO_HXX
TemplateDemo.cpp
#include <iostream>
#include<string>
#include<cstdlib>
#include "TemplateDemo.h"
using namespace std;int main(){Stack<int,20> S20;Stack<int,40> S40;Stack<string,40> Str40;S20.push(7);cout << S20.top() << endl;Str40.push("Hello");cout << Str40.top() << endl;
}
这篇关于类模板非类型形参实现Stack的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!