输出自定义栈所有元素(用友元错误)
这是一个很简单的栈头文件,有个小小的问题在最后的测试程序中有说明了,各位大侠帮忙看下
//Stack.h
#ifndef STACK_H
#define STACK_H
#include <iostream>
using namespace std;
const int CAPACITY=100;
template <class ElementType>
class Stack
{
public:
Stack();//枸造函数
~Stack(){}//析构函数
bool empty()const;//判断栈是否为空
void push(const ElementType &);//压数据入栈
ElementType top()const;//返回栈顶元素
void pop();//删除栈顶元素
friend ostream& operator<<(ostream & out,const Stack<ElementType> & st);//输出整个栈的元素
private:
int MyTop; //指向栈顶元素
ElementType Stack_Array[CAPACITY]; //栈数组
};
template <class ElementType>
inline Stack<ElementType>::Stack()
{
MyTop=-1;
}
template <class ElementType>
bool Stack<ElementType>::empty()const
{
if(MyTop==-1)
return true;
else
return false;
}
template <class ElementType>
void Stack<ElementType>::push(const ElementType &value)
{
if(MyTop < CAPACITY-1)
{
MyTop++;
Stack_Array[MyTop]=value;
}
else
cout<<"Stack_full,please change the CAPACITY in the Stack.h\n";
}
template <class ElementType>
ElementType Stack<ElementType>::top()const
{
if(MyTop!=-1)
return Stack_Array[MyTop];
else
cout<<"Stack_empty!\n";
}
template <class ElementType>
void Stack<ElementType>::pop()
{
if(MyTop!=-1)
MyTop--;
else
cout<<"Stack_empty! Cann't delete!\n";
}
template <class ElementType>
ostream& operator<<(ostream & out,const Stack<ElementType> & st)
{
for(int pos=st.MyTop; pos>=0; pos--)
out<<st.Stack_Array[pos]<<endl;
return out;
}
#endif
测试程序如下:
#include <iostream>
#include "Stack.h"
using namespace std;
int main()
{
Stack<int> intSt;
for(int i=1; i<=4; i++)
intSt.push(i);
while(!intSt.empty())
{
cout<<intSt.top()<<endl;
intSt.pop();
}
for(i=1; i<=4; i++)
intSt.push(i);
cout<<intSt; //这里不行,明明用了友元了为什么还提示不能访问私有变量?(我用的vc++6.0)
getchar();
return 0;
}