C++基础 嵌套类

#ifndef QUEUETP_H_
#define QUEUETP_H_

template<class Item>
class QueueTP
{
private:
    enum{Q_SIZE = 10};
    class Node
    {
    public:
        Item item;
        Node * next;
        Node(const Item & i):item(i),next(0){}
    };
    Node * front;
    Node * rear;
    int items;
    const int qsize;
    QueueTP(const QueueTP &q):qsize(0){}
    QueueTP(const QueueTP *q){return *this;}
public:
    QueueTP(int qs = Q_SIZE);
    ~QueueTP();
    bool isempty() const
    {
        return items == 0;
    }
    bool isfull() const
    {
        return items == qsize;
    }
    int queuecount() const
    {
        return items;
    }
    bool enqueue(const Item &item);    //add item to end
    bool dequeue( Item &item);    //remove item from front

};
// QueueTP methods
template <class Item>
QueueTP<Item>::QueueTP(int qs) : qsize(qs)
{
    front = rear = 0;
    items = 0;
}


template <class Item>
QueueTP<Item>::~QueueTP()
{
    Node * temp;
    while (front != 0)      // while queue is not yet empty
    {
        temp = front;       // save address of front item
        front = front->next;// reset pointer to next item
        delete temp;        // delete former front
    }
}

//add item to queue
template <class Item>
bool QueueTP<Item>::enqueue(const Item &item)
{
    if (isfull())
    {
        return false;
    }
    Node * add = new Node(item);
    if (add == NULL)
    {
        return false;
    }
    items++;
    if (front == 0)
    {
        front = add;
    }
    else
    {
        rear->next = add;
    }
    rear = add;
    return true;
}

// Place front item into item variable and remove from queue
template <class Item>
bool QueueTP<Item>::dequeue(Item & item)
{
    if (front == 0)
        return false;
    item = front->item;     // set item to first item in queue
    items--;
    Node * temp = front;    // save location of first item
    front = front->next;    // reset front to next item
    delete temp;            // delete former first item
    if (items == 0)
        rear = 0;
    return true;
}

#endif
int _tmain(int argc, _TCHAR* argv[])
{
    QueueTP<string> cs(5);
    string temp;
    while( !cs.isfull() )
    {
        cout<<"Please enter your name,you will be served in the order of arrival.\n";
        getline(cin, temp);
        cs.enqueue(temp);
    }
    cout<<"the queue is full.process begins.\n";
    while( !cs.isempty() )
    {
        cs.dequeue(temp);
        cout<<"Now processing "<<temp<<endl;
    }
    system("pause");
    return 0;
}
posted @ 2012-07-26 18:32  Kingdom_0  阅读(367)  评论(0编辑  收藏  举报