定義類模板:
template <class 形參>
class 類名
{.....};
stack.h
#define maxsize 10
template<class type>
class myStack
{
? ? ? ?private:
? ? ? ? ? type object [ maxize];
? ? ? ? ? ?int ?top;
? ? ? public:
? ? ? ? ? ? ? myStack();
? ? ? ? ? ? ?bool push(type e);
? ? ? ? ? ? ?bool pop(type &e);
? ? ? ? ? ? ?void print();
};
template <class type>
myStack <type>::myStack()
{
? ? ? ? ? ? ?top=-1;
}
template <class type>
myStack<type>::push(type e)
{
? ? ?if(top==maxsize-1)
? ? ? ? ? ?return false;
? ? ? esle
? ? ? ? {
? ? ? ? ? ? ? ? e=object[top--];
? ? ? ? ? ? ? ? ?return true;
? ? ? ? }
}
template <class type>
bool myStack<type> ::pop(type &e)
{
? ? ? if(top==-1)
? ? ? ? ? return false;
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? ? ? e=object[top--];
? ? ? ? ? ? ? ? return true;
? ? ? ? ?}
}
template <class type>
void myStack<type>::print()
{
? ? for(int i=0;i<=top;i++)
? ? ? ? ? ? cout<<object[i]<<" ";
? ? cout<<endl;
}
mystack.cpp
#include "stack.h"
#include "iostream"
using namespace std;
int main()
{
myStack<int> s;
int a=6,b=5;
s.push(a);
s.push(b);
s.print();
//由于type可以是任意參數(shù),所以可以拿double嘗試
myStack<double> s2;
double da=2.2,db=3.3;
s2.push(da);
s2.push(db);
s2.print();
cin,get();
return 0;
}