一段关于栈的代码,大家帮我找找错误

来源:百度知道 编辑:UC知道 时间:2024/05/30 11:37:54
// stacks.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream.h"
template <class T>
class stack
{
public:
stack(int max);
~stack()
{delete []stk;};
bool empty()
{return stk_top==-1;
};
bool full()
{return stk_top==max_top;
};
int size()
{return stk_top+1;};
T top();
stack <T>& push(const T &x);
stack <T>& pop(T &x);
void out()
{
for(int i=0;i <stk_top;i++)
{
cout < <stk[i] < <endl;

};
};
private:
int stk_top;
int max_top;
T *stk;
};

template <class T>
stack <T>::stack(int max)
{
max_top=max-1;
stk=new T[max];
stk_top=-1;
}
template <class T>
T stack <T>::top()
{if(empty())throw out_bounds();

1. push函数的返回类型没有必要设置成stack <T>& ,直接返回voidz就行了
2. out函数中for(int i=0;i < stk_top;i++)
把< 改为<=即可。因为你是先增加stk_top的值,再压栈,所以stk_top也指向一个元素。