Template Usage Scenario 2

例:

template <typename T>

class Stack
{
public:
    Stack(int=10);
    ~Stack()
    {
        delete [] stackPtr;           
    }   
    bool push(const T&);
    bool pop(T&);
    bool isEmpty() const
    {
        return top==-1;   
    }
    bool isFull()
    {
        return top==size-1;   
    }
private:
    int size;
    int top;
    T *stackPtr;
};

template <typename T>
Stack<T>::Stack(int s):size(s>0?s:10), top(-1), stackPtr(new T[size])
{

}

bool Stack<T>::push(const T &pushValue)
{
    if(! isFull())
    {
         stackPtr[++top]==pushValue;
         return true;
    }
    return false;
}

bool Stack<T>::pop(T &popValue)
{
    if(! isEmpty())
    {
        popValue=stackPtr[top--];
        return true;   
    }   
    return false;
}

int main()
{
    Stack<double> doubleStack(5);
    double doubleValue=1.1;
    cout<<"Push Value:"<<endl;
    while(doubleStack.push(doubleValue))
    {
        cout<<doubleValue;
        doubleValue+=doubleValue;
    }
    cout<<"/nStack is full. Can't push!"<<endl;

    cout<<"Pop Value: "<<endl;
    while(doubleStack.pop(doubleValue))
    {
        cout<<doubleValue<<" ";
    }
    cout<<"stack is empty. Can't pop!"<<endl;

    return 0;


}

你可能感兴趣的:(Template Usage Scenario 2)