c++ - 将 << 运算符重载为 "friend"函数以打印 BST - C++

标签 c++ operator-overloading binary-search-tree

我正在尝试使 << 过载运算符打印出 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/

相关文章:

c++ - C++ 中的虚拟继承,孙子对象的大小很重?

c++ - Qt SQL - 配置数据库连接

c++ - 错误说定义为公共(public)的类是私有(private)的

c++ - 为什么 operator<< 不适用于 operator- 返回的内容?

c++ - 删除 BST 中的节点时出现运行时错误

Java : setting object to null within a method has no effect (Reusing code)

c++ - 通过结构指针将结构的成员初始化为零

c++ - cout 上抽象类的多态性

c++ - 尝试为枚举重载 operator+= 时出现编译器错误

java - 有什么方法可以从Java中的派生类访问嵌套在父类(super class)中的私有(private)内部类吗?