2014-09-29 129 views
-1

考慮下面的代碼:NULL安全等同於C++運算符

BST.h

#ifndef BST_H 
#define BST_H 

#include <iostream> 

typedef char Key; 
typedef int Value; 
#define NULL 0 

class BST{ 

private: 
    class Node{ 
     Key key; 
     Value value; 
     Node* left; 
     Node* right; 
     int N; 
    public: 
     Node(Key key='A',Value value=NULL,Node* left=NULL,Node* right=NULL,int N=0): 
     key(key),value(value),left(left),right(right),N(N) 
     { 
     std::cout << "(Node created) Key: " << key << " Value : " << value << std::endl; 
     N++; 
     } 
     int getN() 
     { 
     return N; 
     } 
     bool operator==(Node& node) 
     { 

      if (this->key == node.key && this->value == node.value && this->left == node.left && 
       this->right == node.right && this->N == node.N) 
       return true; 
      else 
       return false; 
     } 
    }; 

Node& Root; 

public: 

    int size(); 
    int size(Node& node); 

}; 


#endif 

而且 BST.cpp

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


int BST::size() 
{ 
return size(Root); 
} 

int BST::size(Node& node) 
{ 
if(node == NULL)//here 
    return 0; 
else 
    return node.getN(); 
} 

我得到編譯錯誤的代碼中的//here。解決錯誤

bst.cpp(12): error C2679: binary '==' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion) 
1>   c:\users\gaurav1.k\documents\visual studio 2010\projects\bst\bst\bst.h(30): could be 'bool BST::Node::operator ==(BST::Node &)' 
1>   while trying to match the argument list '(BST::Node, int)' 

的一種方法是改變等於運算符爲: bool operator==(Node* node)

如何,當我路過節點作爲參考.i.e我解決這個錯誤。 bool operator==(Node& node)

感謝

+0

你想用'if(node == NULL)'來測試什麼?如果它是一個「默認」,那麼你可以使用if(node == Node())來代替。 – Niall 2014-09-29 11:07:10

+1

小心你的構造。值不能爲NULL,只有左邊和右邊可以有一個NULL值,因爲它們是唯一的指針。 – 2014-09-29 11:18:18

回答

7

node是一個參考,因此不能NULL0曾經