我正在尝试使 <<
过载运算符打印出 BST 的私有(private)数据(包含单词和计数)。我需要让这个运算符(operator)成为 friend
我的非成员函数 WordTree
类,并且不能定义任何额外的 public
成员函数(这是一项学校作业)。
这是我的 operator<<
友元函数:
ostream& operator<<(ostream &out, const WordTree& rhs)
{
out << InOrder(&out, rhs.root); // does not work as InOrder is private member function
return out;
}
这是我的 private
函数 InOrder
对 BST 执行中序遍历。
ostream& WordTree::InOrder(ostream &out, WordNode* cur)
{
if (cur != nullptr)
{
InOrder(out, cur->m_left);
out << cur->m_data << " " << cur->m_count << endl;
InOrder(out, cur->m_right);
}
return out;
}
有哪些方法可以解决这个问题?
最佳答案
代替
ostream& operator<<(ostream &out, const WordTree& rhs)
{
out << InOrder(&out, rhs.root);
return out;
}
使用
ostream& operator<<(ostream &out, const WordTree& rhs)
{
// Invoke InOrder on the WordTree object.
// Use just out, not &out.
return rhs.InOrder(out, rhs.root);
}
更新,回应OP的评论
很遗憾 InOrder
不是 const
成员函数。应该是一个。
克服这个问题的一种方法是创建一个临时对象并使用它。
ostream& operator<<(ostream &out, const WordTree& rhs)
{
// Invoke InOrder on the WordTree object.
// Use just out, not &out.
WordTree temp(rhs);
return temp.InOrder(out, temp.root);
}
关于c++ - 将 << 运算符重载为 "friend"函数以打印 BST - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885945/