注册 登录
编程论坛 C++教室

超简单自定义类模板栈(友元失效???请进)

晨曦的朝阳 发布于 2008-07-23 21:27, 897 次点击
有个头文件如下(简单的自定义栈类)   //问题后面有说明
//Stack.h
#ifndef STACK_H
#define STACK_H
#include <iostream>
using namespace std;
const int CAPACITY=100;
template <class ElementType>
ostream& operator < <(ostream & out,const Stack <ElementType> & st);  //提示说这里有错,汗

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;
    getchar();
    return 0;
}
错误提示:                     
...\Stack.h(8):error C2143:syntax error:missing ','before ' <'
...\Stack.h(8):error C2059:syntax error:' <'
格式我觉得是没有错的,改了很多次,到底是哪里出问题了?各位帮帮忙,在此谢过!我用的vc++6.0
//template <class ElementType>
//ostream& operator < <(ostream & out,const Stack <ElementType> & st);
如果去掉上面那两行也是不行的,不信试试,说是无法访问私有成员,好像友元失效了???
2 回复
#2
zjl1382008-07-23 22:56
你的代码是不是从网上弄来的."<<"都变成"< <"这样了.

VC6的话,就要自已定义名空间了.
#3
晨曦的朝阳2008-07-23 23:20
就是空间命名污染,已经解决,谢谢2楼。
1