模拟栈行为
// proj2.cpp
#include <iostream>
using namespace std;
class Stack {
public:
virtual void push(char c) = 0;
virtual char pop() = 0;
};
class ArrayStack : public Stack {
char* p;
int maxSize;
int top;
public:
ArrayStack(int s) : maxSize(s), top(0) {
p = new char[maxSize];
}
~ArrayStack() {
delete[] p;
}
void push(char c) {
if (top == maxSize) {
cerr << "Overflow!\n";
return;
}
p[top++] = c;
}
char pop() {
if (top == 0) {
cerr << "Underflow!\n";
return '\0';
}
return p[--top];
}
};
void f(Stack& sRef) {
char ch[] = { 'a', 'b', 'c' };
cout << ch[0] << ", " << ch[1] << ", " << ch[2] << endl;
sRef.push(ch[0]); sRef.push(ch[1]); sRef.push(ch[2]);
cout << sRef.pop() << ", ";
cout << sRef.pop() << ", ";
cout << sRef.pop() << endl;
}
int main() {
ArrayStack as(10);
f(as);
return 0;
}