模板与友元函数出错(山穷水尽了,大侠们都帮帮我吧!)
时间:2008-07-24 16:54:27
来源:论坛整理 作者: 编辑:chinaitzhe
有个头文件如下(简单的自定义栈类)
//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
网友回复:把这2行注释掉:
- C/C code
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ //template <class ElementType> //ostream& operator < <(ostream & out,const Stack <ElementType> & st);
网友回复:你应该把模板类Stack放到
template <class ElementType>
ostream& operator < <(ostream & out,const Stack <ElementType> & st); //提示说这里有错,汗
上面,另外,这句也可以去掉,因为你类里面已经声明它是友元了
网友回复://template <class ElementType>
//ostream& operator < <(ostream & out,const Stack <ElementType> & st);
假如去掉这两句的话,VC中大大出错呀
说是不能访问类的私有成员MyTop还有Stack_Array,我晕死,友元失效了?不信你们用vc编译一下
网友回复:别用vc里的友元啦
网友回复:已经解决了,只要加上自己的命名空间就行了,原来是命名空间污染啊,害我白忙了一大场。
关键字:模板,函数,出错,山穷水尽,大侠,
下一篇:下面没有链接了











文章评论
共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面