我需要帮助重载运算符==,<<,>>用树

时间:2013-12-17 21:42:43

标签: c++ operators overloading

到目前为止,我尝试了很多东西,但它没用。我似乎无法获得任何重载的运算符语法或访问权限。任何人都可以指出我正确的方向如何正确使用这些重载运算符?  头文件。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

#ifndef BINARY_SEARCH_TREE
#define BINARY_SEARCH_TREE

template <typename DataType>
class BST
{
 public:
  /***** Function Members *****/
  BST();
  /*------------------------------------------------------------------------
    Construct a BST object.

    Precondition:  None.
    Postcondition: An empty BST has been constructed.
   -----------------------------------------------------------------------*/

  bool empty() const;
  /*------------------------------------------------------------------------
    Check if BST is empty.

    Precondition:  None.
    Postcondition: Returns true if BST is empty and false otherwise.
   -----------------------------------------------------------------------*/

  bool search(const DataType & item) const; 
  /*------------------------------------------------------------------------
    Search the BST for item.

    Precondition:  None.
    Postcondition: Returns true if item found, and false otherwise.
   -----------------------------------------------------------------------*/

  void insert(const DataType & item);
  /*------------------------------------------------------------------------
    Insert item into BST.

    Precondition:  None.
    Postcondition: BST has been modified with item inserted at proper 
        position to maintain BST property. 
  ------------------------------------------------------------------------*/

  void remove(const DataType & item);
  /*------------------------------------------------------------------------
    Remove item from BST.

    Precondition:  None.
    Postcondition: BST has been modified with item removed (if present);
        BST property is maintained.
    Note: remove uses auxiliary function search2() to locate the node
          containing item and its parent.
 ------------------------------------------------------------------------*/

  void inorder(ostream & out) const;
  /*------------------------------------------------------------------------
    Inorder traversal of BST.

    Precondition:  ostream out is open.
    Postcondition: BST has been inorder traversed and values in nodes 
        have been output to out.
    Note: inorder uses private auxiliary function inorderAux().
 ------------------------------------------------------------------------*/

 //OVER LOADED OPERATORS.

 bool operator==(const BST & right)const;

 //Friend functions.
 friend std::ostream & operator <<(std::ostream & outs, const BST & BinNode) {outs << BinNode.Left()<< " " << BinNode.right();
    return outs;};
 friend std::istream & operator >>(std::istream& ins, BST & target) {ins << target.left << " " << target.right;
 return ins;};

 //Insertion of the file using a text tile.
 void readFile();



 private:
  /***** Node class *****/
  class BinNode 
  {
   public:

    DataType data;
    BinNode * left;
    BinNode * right;

    // BinNode constructors
    // Default -- data part is default DataType value; both links are null.
    BinNode()
    {
        left = 0;
        right = 0;}

    // Explicit Value -- data part contains item; both links are null.
    BinNode(DataType item)
    {
        data = item; 
        left = 0;
        right = 0;
    }

  };// end of class BinNode declaration

  typedef BinNode * BinNodePointer; 

  /***** Private Function Members *****/
  void search2(const DataType & item, bool & found,
               BinNodePointer & locptr, BinNodePointer & parent) const;
 /*------------------------------------------------------------------------
   Locate a node containing item and its parent.

   Precondition:  None.
   Postcondition: locptr points to node containing item or is null if 
       not found, and parent points to its parent.#include <iostream>
 ------------------------------------------------------------------------*/

  void inorderAux(ostream & out, 
                  BinNodePointer subtreePtr) const;
  /*------------------------------------------------------------------------
    Inorder traversal auxiliary function.

    Precondition:  ostream out is open; subtreePtr points to a subtree 
        of this BST.
    Postcondition: Subtree with root pointed to by subtreePtr has been
        output to out.
 ------------------------------------------------------------------------*/


 /***** Data Members *****/
  BinNodePointer myRoot; 

}; // end of class template declaration

//--- Definition of constructor
template <typename DataType>
inline BST<DataType>::BST()
{myRoot = 0;}

//--- Definition of empty()
template <typename DataType>
inline bool BST<DataType>::empty() const
{ return myRoot == 0; }

//--- Definition of search()
template <typename DataType>
bool BST<DataType>::search(const DataType & item) const
{
   BinNodePointer locptr = myRoot;
   bool found = false;
   while (!found && locptr != 0)
   {
      if (item < locptr->data)       // descend left
        locptr = locptr->left;
      else if (locptr->data < item)  // descend right
        locptr = locptr->right;
      else                           // item found
        found = true;
   }
   return found;
}

//--- Definition of insert()
template <typename DataType>
inline void BST<DataType>::insert(const DataType & item)
{
   BinNodePointer 
        locptr = myRoot,   // search pointer
        parent = 0;        // pointer to parent of current node
   bool found = false;     // indicates if item already in BST
   while (!found && locptr != 0)
   {
      parent = locptr;
      if (item < locptr->data)       // descend left
         locptr = locptr->left;
      else if (locptr->data < item)  // descend right
         locptr = locptr->right;
      else                           // item found
         found = true;
   }
   if (!found)
   {                                 // construct node containing item
      locptr = new BinNode(item);  
      if (parent == 0)               // empty tree
         myRoot = locptr;
      else if (item < parent->data )  // insert to left of parent
         parent->left = locptr;
      else                           // insert to right of parent
         parent->right = locptr;
   }
   else
      cout << "Item already in the tree\n";
}

//--- Definition of remove()
template <typename DataType>
void BST<DataType>::remove(const DataType & item)
{
   bool found;                      // signals if item is found
   BinNodePointer 
      x,                            // points to node to be deleted
      parent;                       //    "    " parent of x and xSucc
   search2(item, found, x, parent);

   if (!found)
   {
      cout << "Item not in the BST\n";
      return;
   }
   //else
   if (x->left != 0 && x->right != 0)
   {                                // node has 2 children
      // Find x's inorder successor and its parent
      BinNodePointer xSucc = x->right;
      parent = x;
      while (xSucc->left != 0)       // descend left
      {
         parent = xSucc;
         xSucc = xSucc->left;
      }

     // Move contents of xSucc to x and change x 
     // to point to successor, which will be removed.
     x->data = xSucc->data;
     x = xSucc;
   } // end if node has 2 children

   // Now proceed with case where node has 0 or 2 child
   BinNodePointer 
      subtree = x->left;             // pointer to a subtree of x
   if (subtree == 0)
      subtree = x->right;
   if (parent == 0)                  // root being removed
      myRoot = subtree;
   else if (parent->left == x)       // left child of parent
      parent->left = subtree; 
   else                              // right child of parent
      parent->right = subtree;
   delete x;
}

//--- Definition of inorder()
template <typename DataType>
inline void BST<DataType>::inorder(ostream & out) const
{ 
   inorderAux(out, myRoot); 
}


//--- Definition of search2()
template <typename DataType>
void BST<DataType>::search2(const DataType & item, bool & found,
                            BinNodePointer & locptr, 
                            BinNodePointer & parent) const
{
   locptr = myRoot;
   parent = 0;
   found = false;
   while (!found && locptr != 0)
   {
      if (item < locptr->data)       // descend left
      {
         parent = locptr;
         locptr = locptr->left;
      }
      else if (locptr->data < item)  // descend right
      {
         parent = locptr;
         locptr = locptr->right;
      }
      else                           // item found
         found = true;
   }
}

//--- Definition of inorderAux()
template <typename DataType>
void BST<DataType>::inorderAux(ostream & out, 
                               BinNodePointer subtreeRoot) const
{
   if (subtreeRoot != 0)
   {
      inorderAux(out, subtreeRoot->left);    // L operation
      out << subtreeRoot->data << "  ";      // V operation
      inorderAux(out, subtreeRoot->right);   // R operation
   }
}

//---Overloading the Operator double equals.
template <typename DataType>
bool BST<DataType>::operator ==(const BST& right) const
{
     //Postcondition: The value returned is true if p1 and p2
     // are identical; otherwise false returned.
    return (BinNodePointer.right == BinNodePointer.right) && (BinNodePointer.left == BinNodePointer.left);

}

//tried to put all operations here to see a clean main with just function calls.
 template<typename DataType>
 void BST<DataType>::readFile()
 {
      BST<string> start;

      string data,motor;

     ifstream infile;
    infile.open("Tree.txt");
        if (infile.fail( ))
                {
                    cout << "Input infile opening failed.\n";
                    exit(1);
                }
      getline(infile, data); 
        while (! infile.eof( ))
                {
                    start.insert(data);
                    cout << data <<endl;
                    getline(infile, data); 
                } 

     cout<< "\n\nStarting a binary search tree.\n"
         << "\nEnter the ID & Password you wish to compare: ";



    /*  if(start.operator==(motor))
            cout << "They are equal.";
        else
         cout <<"they are not equal.";
         */
         //cout << start.inorder(data);
 }


#endif

这是我的main.ccp,我在编写重载操作符后基本上开始测试,并且自从调整它们以来,我花了大约2天的时间试图弄清楚在调整后我无法访问任何成员函数。

#include<iostream>
#include<fstream>
#include"BST.h"

using namespace std;

int main()

{
    BST<string> C;

    C.readFile();
    C.empty();
    C.insert("myself");
    cout << C;
        system("pause");
        return 0;
}

我查看了==<<>>的运算符示例,但我从未遇到过使用二叉搜索树的任何有用的内容。

例如。

我正在尝试使用

输出已在二进制搜索树中的内容
cout << C;

使用

friend std::ostream & operator <<(std::ostream & outs, const BST & BinNode) {outs << BinNode.Left<< " " << BinNode.right;
    return outs;};

这是我从主要调用ostream(cout&lt;&lt; C;)得到的错误

Error   1   error C2039: 'Left' : is not a member of 'BST<DataType>'
Error   2   error C2039: 'right' : is not a member of 'BST<DataType>'

另外,从我的readFile()函数我试图使运算符==,将传入的字符串与已经在树内的字符串进行比较,但似乎我需要使运算符成为指向该类的指针

template <typename DataType>
bool BST<DataType>::operator ==(const BST& right) const
{
     //Postcondition: The value returned is true if p1 and p2
     // are identical; otherwise false returned.
    return (BinNodePointer.right == BinNodePointer.right) && (BinNodePointer.left == BinNodePointer.left);

}

↑这就是杀了我的原因。我似乎无法做正确的比较,我使用的教科书没有给我一个很好的例子,所以我正在寻求帮助。

由于我无法发布答案,我将尝试在此发帖..

当我尝试使用以下函数调用operator == readFile()函数时:

if(start.operator==(motor))
    cout << "They are equal.";
else
 cout <<"they are not equal.";

我收到错误:

Error   1   error C2664: 'BST<DataType>::operator ==' : cannot convert parameter 1 from 'std::string' to 'const BST<DataType> &'    

2 个答案:

答案 0 :(得分:1)

template <typename DataType>
bool BST<DataType>::operator ==(const BST& right) const
{
     //Postcondition: The value returned is true if p1 and p2
     // are identical; otherwise false returned.
    //return (BinNodePointer.right == BinNodePointer.right) && (BinNodePointer.left == BinNodePointer.left);
    return (*right == *(right.right)) && (*left == *(right.left));

}

答案 1 :(得分:-1)

有一件事看起来不对:

template <typename DataType>
bool BST<DataType>::operator ==(const BST& right) const
{
     //Postcondition: The value returned is true if p1 and p2
     // are identical; otherwise false returned.
     return (BinNodePointer.right == BinNodePointer.right) && 
             (BinNodePointer.left ==   BinNodePointer.left);

}

,其中

 typedef BinNode * BinNodePointer; 

你试图直接从一个类型名称中获取一个字段值,我认为这在大多数(每个?)上下文中都是错误的。

有助于了解您所看到的错误类型以及它们出现在哪条线上

编辑: BinNodePointer是类型。它不包含或指向任何数据,只包含数据的“形状”。

它描述了一个指向BinNode的指针。所以你的代码等同于:

return ((BinNode *).right == (BinNode *).right) && 
         ((BinNode *).left ==   (BinNode *).left);