我必须为类分配实现一个名为 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 并提供了命名空间。
最佳答案
您不能引用未声明的 Stack<T>
在operator<<
声明。您需要前向声明 template<class T> Stack;
在 Stack.h 的顶部,或在包含它的每个文件中包含 Stack.h 之前。
关于c++ - 我的模板重载 << 运算符有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21638954/