c++ - 我的模板重载 << 运算符有什么问题?

标签 c++ templates operator-overloading

我必须为类分配实现一个名为 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/

相关文章:

c++ - 我可以使单个模板<typename T> 应用于多个定义/声明吗?

c++ - 为什么 protected 继承会导致 dynamic_cast 失败?

c++ - 为什么 int a; a = std::max(a, x) 不发出 "uninitialized"警告

C++ 我应该如何返回我的字节数组?

C#语法糖重载

c++ - 成为左操作数意味着什么?

c++ - 在 C++ 中尝试在每个运算符重载级联之后写一个换行符

c++ - 可以在不取消引用的情况下增加指针仍然是段错误或具有其他(未)定义的肮脏吗?

c++ - boost spirit 的帮助函数(具有模板化返回类型的模板)

ruby-on-rails - 让用户为自定义布局编写数据库存储的 CSS