code/C++
[C++] Stack&Queue (예외처리, 소멸자 포함)
shallot
2017. 4. 20. 14:04
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | #include<iostream> using namespace std; const int MAX = 10; class Memory { protected: int *data; int top; int front; public: Memory() { data = new int[10]; top = 0; } void push(int num) { if (top == MAX) { cout << "FULL!!" << endl; return; } else { data[top++] = num; } } virtual int pop() = 0; virtual ~Memory() { delete[]data; cout << "소멸자 함수" << endl; } }; class Stack :public Memory { public: int pop() { if (top == 0) { cout << "EMPTY!!!" << endl; return 0; } else { return data[--top]; } } }; class Queue :public Memory { public: Queue() { front = 0; } int pop() { if (top == front) { cout << "EMPTY!!!" << endl; return 0; } else { if (front==MAX) { front = 0; } return data[(front++)]; } } }; void main() { Stack s; Queue q; Memory *p; int num; int a; do { cout << "1.stack" << "\t" << "2.queue" << "\t" << "3.Quit" << endl; cin >> num; if (num == 1) { p = &s; } else if (num == 2) { p = &q; } else if (num == 3) { continue; } else { cout << "Not num" << endl; cout << "Bye" << endl; num = 3; continue; } cout << "1.push" << "\t" << "2.pop" << endl; cin >> num; if (num == 1) { cout << "Data input : "; cin >> a; p->push(a); } else { cout << " output Data : " << p->pop() << endl; } } while (num != 3); } |