C++模板類+巢狀類例項
阿新 • • 發佈:2018-12-29
queue.h
queue.cpp#ifndef QUEUE_H_ #define QUEUE_H_ template<class Type> class Queue{ private: enum {Q_SIZE = 10}; class Node{ public: Type data; Node * next; Node(const Type data) : data(data), next(0) {} }; Node *front; Node *rear; int curSize; int maxSize; public: Queue(int size = Q_SIZE); ~Queue(); bool isFull() const; bool isEmpty() const ; bool enQueue(const Type data); bool deQueue(); void tarverseQueue() const; }; #endif
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <valarray> #include "queue.h" using std::cout; using std::endl; template<class Type> Queue<Type>::Queue(int size) : maxSize(size) { front = rear = 0; curSize = 0; } template<class Type> Queue<Type>::~Queue() { Node *tmp; while (front != 0) { tmp = front; front = front->next; delete tmp; } } template<class Type> bool Queue<Type>::isFull() const { return curSize >= maxSize; } template<class Type> bool Queue<Type>::isEmpty() const { return curSize == 0; } template<class Type> bool Queue<Type>::enQueue(const Type data) { if (isFull()) { return false; } Node *node = new Node(data); if (front == 0) { front = node; } else { rear->next = node; } rear = node; curSize++; return true; } template<class Type> bool Queue<Type>::deQueue() { if (isEmpty()) { return false; } Node *tmpNode = front; front = front->next; delete tmpNode; if (front == 0) { rear = 0; } curSize--; return true; } template<class Type> void Queue<Type>::tarverseQueue() const { Node *head = front; while (head != 0) { cout << head->data << endl; head = head->next; } } int main(int argc, char *argv[]) { Queue<int> queue(10); queue.enQueue(11); queue.enQueue(12); queue.tarverseQueue(); return 0; }