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