【问题标题】:Trouble with the STL in a Friend FunctionFriend 函数中的 STL 问题
【发布时间】:2012-10-25 00:20:59
【问题描述】:

我正在研究二叉搜索树类,但在编写重载流操作符函数时遇到了问题。这是我的代码...我已经完成了我在网上找到的所有内容(以及在我教授的简报中),所以我不知道我做错了什么。

*几秒钟前编辑以更新对我的代码的更改。决定从正在发送给朋友的对象调用函数,该函数与朋友函数中的代码相似......

头文件(.h文件)中的相关头文件:

friend ostream& operator<<(ostream& out, const BST& tree);

void leveltraversal(ostream& out);

头文件(.h 文件)中的相关“私有”数据/嵌套类:

private:
  class BinNode {
  public:
    T data;
    BinNode* left;
    BinNode* right;
    BinNode() : left(NULL), right(NULL) {}
      BinNode (T item): data(item), left(NULL), right(NULL) {}
  };

  typedef BinNode* BinNodePtr;
  BinNodePtr myRoot;

相关实现文件功能:

ostream& operator<<(ostream& out, const BST& tree)
{
  tree.leveltraversal(out);
  return out;
}

template <typename T>
void BST<T>::leveltraversal(ostream& out)
{
  int level = 0;
  BinNodePtr temp = myRoot;
  queue<BinNodePtr> nodes;
  nodes.push(temp);
  out << endl << endl;
  while (!nodes.empty()){
      temp = nodes.front();
      level = recursive_level(temp->data);
      out << endl << endl;
      out << "Node data: " << temp->data;
      out << endl;
      out << "Level: " << level;
      nodes.pop();
      if (temp->left)
        nodes.push(temp->left);
      if (temp->right)
        nodes.push(temp->right);
  }
}

我会发布编译器错误,但它们持续了好几行,我觉得问题是不言而喻的。不过,如果有人愿意,将与他们一起更新!

【问题讨论】:

  • 您可能希望包含编译器错误/警告
  • 哦,是的!抱歉...我整天都在编码,有点累了。感谢您的帮助:)
  • 很难说没有错误消息(第一个(或几个)通常就足够了),但首先:你用什么实例化BST 模板,即什么是temp-&gt;data?

标签: c++ stl implementation binary-search-tree friend


【解决方案1】:

由于您没有列出错误消息,甚至没有说明您遇到的问题类型,因此很难提供帮助。但是我尝试填写一些空白来复制您的问题,并发现代码存在一些问题:

template <typename T>
class BST {
   ...
   friend std::ostream& operator<<(std::ostream& out, const BST& tree)
   {
       tree.leveltraversal(out);
       return out;
   }
  • operator&lt;&lt; 中,您使用const BST&amp; tree(意味着您不能通过此引用更改原始对象),因此leveltraversal 函数也必须声明为const。您不能在const 对象上调用非const 成员函数;如果允许,您可以修改对象,从而破坏constness。
void leveltraversal(std::ostream& out) const;

通过这些更改,使用 clang 和 g++ 为我构建了适合我的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多