【发布时间】:2014-02-07 22:29:23
【问题描述】:
我必须为类分配实现一个名为Stack 的模板类。 Stack 有一个重载的流插入操作符。
以下是 Stack.h 文件的相关摘录:
...
#include <iostream>
using namespace std;
template<class T>
ostream& operator<<(ostream&,Stack<T>&);
template<class T>
class Stack
{
public:
friend ostream& operator<< <T>(ostream&,Stack<T>&);
...
};
#include "Stack.cpp"
...
我无法更改 Stack.h,因为它是按原样提供的。 Stack.cpp 的相关摘录是:
template <class T>
ostream& operator<< (ostream& out, Stack<T>& stack)
{
Stack<T>::Node* current = stack.top;
out << "[";
while (current)
{
out << current->element;
current = current->next;
if (current)
out << ",";
}
out << "]";
return out;
}
...
这在 Visual Studio 中编译和工作正常,但是,当使用 g++ 编译时,它会给出以下错误:
Stack.cpp:4: syntax error before '&'
Stack.cpp:4: 'ostream' was not declared in this scope
Stack.cpp:4: 'out' was not declare din this scope
Stack.cpp:4: 'Stack' was not declared in this scope
Stack.cpp:4: 'T' was not declared in this scope
Stack.cpp:4: 'stack' was not declared in this scope
Stack.cpp:5: declaration of 'operator <<' as non-function
这是为什么呢?有什么办法可以解决?
编辑:我补充说我已经包含了 iostream 并提供了命名空间。
【问题讨论】:
-
#include <iostream>,#include "Stack.h"? -
还有
typename Stack<T>::Node* current = ... -
Node 是一个在 Stack 内部定义的类。
-
你需要
typename。 -
可能是您正在尝试编译
Stack.cpp。
标签: c++ templates operator-overloading