我分不清这段代码的哪一部分是错的。 错误信息如下所示。
我想重载<<
运算符,这样我就可以编写类似cout<<<; 树
。 我查找有关模板,朋友函数,操作符重载的信息。 但我还是不明白为什么会出错。
template <typename Value> class Tree { protected: Node<Value>* root = NULL; int size = 0; std::ostream& _ostreamOperatorHelp(Node<Value>* node, int level, std::ostream& os) { ... } public: friend std::ostream& operator<< <Value>(std::ostream& os, Tree<Value> const& tree); }; template <typename Value> std::ostream& operator<<(std::ostream& os, Tree<Value> const& tree) { tree._ostreamOperatorHelp(tree.GetRoot(), 0, os); return os; }
错误消息:
Tree.hpp:129:34: error: declaration of 'operator<<' as non-function
friend std::ostream& operator<< <Value>(std::ostream& ,
^~
在您能够与特定模板专门化套近乎之前,您必须先像这样声明通用模板函数:
template <typename Value>
class Tree;
template <typename Value>
std::ostream& operator<<(std::ostream& os, Tree<Value> const& tree);
template <typename Value>
class Tree {
protected:
Node<Value>* root = NULL;
int size = 0;
std::ostream& _ostreamOperatorHelp(Node<Value>* node, int level,
std::ostream& os) {
...
}
public:
friend std::ostream& operator<< <Value>(std::ostream& os,
Tree<Value> const& tree);
};
template <typename Value>
std::ostream& operator<<(std::ostream& os, Tree<Value> const& tree) {
tree._ostreamOperatorHelp(tree.GetRoot(), 0, os);
return os;
}