C++ 嵌套类

嵌套类的定义

queuetp.h

  1. #ifndef PRO1_QUEUETP_H
  2. #define PRO1_QUEUETP_H
  3. #include <cstring>
  4. template <class Item>
  5. class QueueTP {
  6. private:
  7. enum {Q_SIZE = 10};
  8. // Node is a nested definition
  9. class Node{
  10. public:
  11. Item item;
  12. Node *next;
  13. Node(const Item & i):item(i), next(0){}
  14. };
  15. Node * front;
  16. Node * rear;
  17. int items;
  18. const int qsize;
  19. QueueTP(const QueueTP & q):qsize(0){}
  20. QueueTP &operator=(const QueueTP & q){ return *this; }
  21. public:
  22. QueueTP(int qs = Q_SIZE);
  23. ~QueueTP();
  24. bool isempty()const { return items == 0; }
  25. bool isfull()const { return items == qsize; }
  26. int queuecount()const { return items; }
  27. bool enqueue(const Item &item);
  28. bool dequeue(Item &item);
  29. };
  30. // QueueTP methods
  31. template <class Item>
  32. QueueTP<Item>::QueueTP(int qs):qsize(qs) {
  33. front = rear = 0;
  34. items = 0;
  35. }
  36. template <class Item>
  37. QueueTP<Item>::~QueueTP() {
  38. Node *temp;
  39. while (front != 0) {
  40. temp = front;
  41. front = front->next;
  42. delete temp;
  43. }
  44. }
  45. // Add item to queue
  46. template <class Item>
  47. bool QueueTP<Item>::enqueue(const Item &item) {
  48. if (isfull())
  49. return false;
  50. Node * add = new Node(item);
  51. if(add == NULL)
  52. return false;
  53. items++;
  54. if(front == 0)
  55. front = add;
  56. else
  57. rear->next = add;
  58. rear = add;
  59. return true;
  60. }
  61. // Place front item into item variable and remove from queue
  62. template <class Item>
  63. bool QueueTP<Item>::dequeue(Item &item) {
  64. if (front == 0)
  65. return false;
  66. item = front->item;
  67. items--;
  68. Node *temp = front;
  69. front = front->next;
  70. delete temp;
  71. if (items == 0)
  72. rear = 0;
  73. return true;
  74. }
  75. #endif //PRO1_QUEUETP_H

queuetp.cpp

  1. #include "queuetp.h"

嵌套类的使用

main.cpp

  1. #include <iostream>
  2. #include <string>
  3. #include <cstring>
  4. #include "module13_nesting/template_nesting/queuetp.h"
  5. using namespace std;
  6. // 嵌套类的使用
  7. void useNestClass(){
  8. QueueTP<string> cs(5);
  9. string temp;
  10. while (!cs.isfull()) {
  11. cout << "Please enter your name. You will be served in the order of arrival.\n name: ";
  12. getline(cin, temp);
  13. cs.enqueue(temp);
  14. }
  15. cout << "The queue is full. Processing bedins!\n";
  16. while (!cs.isempty()) {
  17. cs.dequeue(temp);
  18. cout << "Now processing " << temp << "...\n";
  19. }
  20. }
  21. int main() {
  22. useNestClass();
  23. return 0;
  24. }