NULL安全等于C++中的运算符

NULL safe equal to operator in C++

本文关键字:运算符 C++ 安全 NULL      更新时间:2023-10-16

考虑以下代码:

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:usersgaurav1.kdocumentsvisual studio 2010projectsbstbstbst.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)

当我将节点作为引用传递时,如何解决此错误。即。bool operator==(Node& node)

感谢

node是一个引用,因此它不能NULL0