急求一个用c++类编的程序,能实现栈的基本操作,并重载下标运算符

2025-04-02 13:17:55
推荐回答(1个)
回答1:

#define MAX_SIZE 1000
template
class Stack
{
public:
Stack(void):index(-1) { }
void push(T v) { values[++index] = v; }
T pop(void) { return values[index--]; }
private:
T values[MAX_SIZE];
int index;
};

void main(void)
{
int r;
Stack ss;
ss.push(1);
ss.push(2);
ss.push(3);
printf("Stack value is: %d\r\n",ss.pop());
printf("Stack value is: %d\r\n",ss.pop());
printf("Stack value is: %d\r\n",ss.pop());
}

output value:
Stack value is: 3
Stack value is: 2
Stack value is: 1