2012-11-05 51 views
2

我正在研究Binary Search Tree类,并且无法编码重载流操作函数。这是我的代码...我已经完成了我在网上找到的一切(以及我的教授的权力点),所以我不知道我做错了什么。STL在朋友函数中的问题

*编辑几秒钟前更新我的代码更改。决定要求从目标函数被发送到具有类似的代码到这是在友元函数的朋友......

在头文件的相关头(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); 
    } 
} 

我会发布编译器错误,但他们继续了很多行,我觉得这些问题是不言而喻的。不过,如果有人愿意,他们会更新!

+3

你可能想要包含编译器错误/警告 – gvd

+0

噢!对不起......我整天都在编码,而且有点累。感谢您的帮助:) – user1799411

+0

很难说没有错误信息(第一个(或几个)通常就足够了),但首先,你是在用什么实例化'BST'模板,即什么是'temp - > data'? – molbdnilo

回答

0

由于您没有列出错误消息,甚至没有说明您遇到的问题类型,所以很难提供帮助。但是我试图填补空白的一些复制您的问题,并发现了几个与代码的问题:

template <typename T> 
class BST { 
    ... 
    friend std::ostream& operator<<(std::ostream& out, const BST& tree) 
    { 
     tree.leveltraversal(out); 
     return out; 
    } 
  • operator<<你把const BST& tree(这意味着你不能改变原来的对象,虽然这个参考),因此leveltraversal功能必须也被宣布为const。您不能在const对象上调用非const成员函数;如果允许的话,可以让你修改对象,打破const
void leveltraversal(std::ostream& out) const; 

随着这些变化,我用clang和g ++编译的代码都很好。