//Stack.h
#ifndef _STACK_H_
#define _STACK_H_
template<typename T>
class Stack
{
private:
int size;//栈中元素个数
int top;//栈顶元素位置
T *stackPtr;
public:
Stack(int = 10);
~Stack()
{
delete [] stackPtr;
}
bool push(const T&);
bool pop(T&);
bool isEmpty() const
{
return top == -1;
}
bool isFull() const
{
return top == size-1;
}
};
template<typename T>
Stack<T>::Stack(int s)
:size(s > 0 ? s : 10),
top(-1),
stackPtr(new T[size])
{
//empty body
}
template<typename T>
bool Stack<T>::push(const T &pushValue)
{
if(!isFull())
{
stackPtr[++top] = pushValue;
return true;
}
return false;
}
template<typename T>
bool Stack<T>::pop(T &popValue)
{
if(!isEmpty())
{
popValue = stackPtr[top--];
return true;
}
return false;
}
#endif
//testMain.cpp
#include <iostream>
using namespace std;
#include "Stack.h"
int main()
{
Stack<double> doubleStack(5);
double doubleValue = 1.2;
cout << "Pushing elements onto doubleStack" << endl;
while(doubleStack.push(doubleValue))
{
cout << doubleValue << ' ';
doubleValue += 1.2;
}
cout << "\nStack is full.Cannot push " <<doubleValue
<< "\nPoping elements from doubleStack.\n";
while(doubleStack.pop(doubleValue))
cout << doubleValue << " ";
cout << "\nstack is empty,Cannot pop." << endl;
Stack<int> intStack;
int intValue = 1;
cout << "Pushing elements onto intStack" << endl;
while(intStack.push(intValue))
{
cout << intValue << ' ';
intValue ++;
}
cout << "\nStack is full.Cannot push " <<intValue
<< "\nPoping elements from intStack.\n";
while(intStack.pop(intValue))
cout << intValue << " ";
cout << "\nstack is empty,Cannot pop." << endl;
system("pause >> cout");
return 0;
}
//创建函数模版来测试类模版Stack<T>
#include <iostream>
#include <string>
using namespace std;
#include "Stack.h"
template <typename T>
void testStacks(Stack<T> theStack,
T value,
T increment,
const string StackName)
{
cout << "Pushing elements onto " << StackName << endl;
while(theStack.push(value))
{
cout << value << " ";
value += increment;
}
cout << "\nStack is full,Cannot push " << value
<< "\nPoping elements from " << StackName << endl;
while(theStack.pop(value))
{
cout << value << " ";
}
cout << "\nStack is empty,Cannot pop." << endl;
}
int main()
{
Stack<double> doubleStack(5);
Stack<int> intStack;
testStacks(intStack,1,3,"intStack");
testStacks(doubleStack,1.2,2.3,"doubleStack");
system("pause >> cout");
return 0;
}