函数模板和类模板程序举例及个别心里体会

xiaoxiao2021-02-28  42

栈类模板的使用   (用多文件程序编写)

       //注意事项   类模板的声明和定义都要写在头文件里,否则发生错误

#include<iostream> #include<string.h> using namespace std; template<typename Type> class Stack { public:     Stack(int=10);     ~Stack()     {         delete stackPtr;     }     int push(const Type&);     int pop(Type&);     int isFull() const     {         return top==size-1;     }     int isEmpty() const     // const 放在函数后表示这个函数是常成员函数, 常成员函数是不能改变成员变量值的函数     {         return top==-1;     } private:     int size;     int top;     Type* stackPtr; }; template<typename Type> Stack<Type>::Stack(int s) {     size=(s>0&&s<1000?s:10);     top=-1;     stackPtr=new Type[size]; } template<typename Type> int Stack<Type>::push(const Type& item) {     if(!isFull())     {         stackPtr[top++]=item;                             return 1;     }     return 0; } template<typename Type> int Stack<Type>::pop(Type& popValue) {     if(!isEmpty())     {         popValue=stackPtr[--top];         return 1;     }     return 0; }

#include"Stack.h" int main() {     Stack<char> charStack;                 //创建字符型栈对象  charStack     char c='a';     cout<<"Pushing elements onto charStack "<<endl;     while(charStack.push(c))     {         cout<<c<<" ";         c+=1;     }     cout<<endl<<"Stack is full can not push "<<c<<endl     <<"Poping elements from charStack "<<endl;     while(charStack.pop(c))     cout<<c<<" ";     cout<<endl<<"Stack is empty can not pop "<<endl;     Stack<double> doubleStack(5);                                     //创双精度型栈对象  doubleStack     double f=1.1;     cout<<"Pushing elements onto doubleStack "<<endl;     while(doubleStack.push(f))     {         cout<<f<<" ";         f+=1.1;     }     cout<<endl<<"Stack is full can not push "<<f<<endl     <<"poping elements from doubleStack "<<endl;     while(doubleStack.pop(f))     {         cout<<f<<" ";     }     cout<<endl<<"Stack is empty cannot pop"<<endl;     Stack<int> intStack;                                          //创建整型栈对象  intStack     int i=1;     cout<<"Pushing elements onto intStack "<<endl;     while(intStack.push(i))     {         cout<<i<<" ";         i+=1;     }     cout<<endl<<"Stack is full cannot push "<<i<<endl     <<"poping elements from intStack "<<endl;     while(intStack.pop(i))     cout<<i<<" ";     cout<<endl<<"Stack is empty cannot pop"<<endl; }

转载请注明原文地址: https://www.6miu.com/read-78537.html

最新回复(0)