我正在制作我的第一个二叉搜索树。我在BinarySearchTree中嵌套了BinarySearchTreeNode。我试图重载<<<<< BinarySearchTreeNode的运算符,但我无法弄清楚如何编译它。
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#navigation_bar {
background-color: black;
position: absolute;
height: 10%;
width: 100%;
}
.home_body {
background-color: green;
height: 60%;
width: 100%;
}
.lower_home_body {
width: 100%;
height: 20%;
background-color: blue;
}
.footer_bar {
width: 100%;
height: 10%;
background-color: black;
}
这不会编译,因为它说命名空间cs20a中没有匹配的声明。我无法弄清楚如何编译它。我能让它工作的唯一方法是将函数定义放在顶部而不是在顶部声明它。我的教授希望他们在可能的情况下分开。
谢谢
答案 0 :(得分:1)
您可以在命名空间定义的最后添加声明:
// ... ...
};
};
template<class Type>
std::ostream& operator <<(std::ostream &outs, const typename BinarySearchTree<Type>::BinarySearchTreeNode& node);
}
template<class Type>
std::ostream& cs20a::operator <<(std::ostream &outs, const typename BinarySearchTree<Type>::BinarySearchTreeNode& node)
{
outs << node.getData();
return outs;
}
答案 1 :(得分:0)
这是一个使用g ++ 4.8.4为我成功构建的骨架程序。 我在代码中添加了注释来解释我所做的事情。
#include <iostream>
using namespace std;
namespace cs20a
{
// Declare the class template.
template <class Type> class BinarySearchTree;
// Declare the operator<<() function.
template <typename T> std::ostream& operator<<(std::ostream &outs,
const typename BinarySearchTree<T>::BinarySearchTreeNode& node);
template<class Type> class BinarySearchTree
{
public:
BinarySearchTree();
class BinarySearchTreeNode
{
// Make operator<<() a friend.
// This syntax makes sure that operator<< <int> is a friend of
// BinarySearchTree<int>::BinarySearchTreeNode but not a friend
// of BinarySearchTreeNode<double>::BinarySearchTreeNode.
friend std::ostream& operator<< <Type>(std::ostream &outs, const BinarySearchTreeNode& node);
public:
const Type &getData() const;
};
private:
BinarySearchTreeNode *head;
};
}
// Implement the function.
template<class Type>
std::ostream& cs20a::operator<<(std::ostream &outs,
const typename BinarySearchTree<Type>::BinarySearchTreeNode& node)
{
outs << node.getData();
return outs;
}
int main()
{
return 0;
}