输出自定义栈所有元素(用友元错误)

那个天真的人 2008-07-22 11:56:07
这是一个很简单的栈头文件,有个小小的问题在最后的测试程序中有说明了,各位大侠帮忙看下
//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;
}

...全文
127 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
lzr4304061988012 2008-07-23
  • 打赏
  • 举报
回复
因为是友员,毕竟不是类的成员,你不将他声明为模板,编译器不会理解的!
lzr4304061988012 2008-07-23
  • 打赏
  • 举报
回复
在 CLASS STACK 之前声明template <class type> ostream& operator < <(ostream & out,const Stack <type> & st);
那个天真的人 2008-07-23
  • 打赏
  • 举报
回复
难道是VC的问题吗,楼上的意思?
taodm 2008-07-23
  • 打赏
  • 举报
回复
你就扔了VC6吧,别用它浪费生命了。
那个天真的人 2008-07-23
  • 打赏
  • 举报
回复
还是不行呀,看来得重发贴了,跑到太后了,还是谢谢你。

64,647

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧