Visual c++ C++二叉树过载

Visual c++ C++二叉树过载,visual-c++,Visual C++,我创建了一个包含一个字符和一个字符串的stuct struct M2E { char english; string morse;} 通过使用给出的代码,我创建了M2E的二叉树,即bintree 但我想把这些M2E按字符串莫尔斯顺序排序*小于- 所以我在结构M2E中进行了运算符重载 bool operator == (M2E& other) const { return morse.compare(other.morse); } 但是当我编译时,我一直给出下面的错误消

我创建了一个包含一个字符和一个字符串的stuct

 struct M2E
 { char english;
 string morse;}
通过使用给出的代码,我创建了M2E的二叉树,即bintree 但我想把这些M2E按字符串莫尔斯顺序排序*小于- 所以我在结构M2E中进行了运算符重载

 bool operator == (M2E& other) const
{
    return morse.compare(other.morse);
}
但是当我编译时,我一直给出下面的错误消息

no match for "operator ==" in ((binNode<M2E>*)this)->binNode<M2E>::nodeData == dataItem
note:candidates are :bool M2E::operator==(M2E&) const
我用于二叉树的代码是bintree.h:

  template <typename dataType> class bintree
{  
  private:
  binNode<dataType> *root;
  int numItems;

  void insert(const dataType& newData) 
  {
     // insert the newData into the tree

     if (root == NULL) 
     {
        root = new binNode<dataType>(newData);
     } 
     else 
     {
        root->insert(root, newData);
     }
     numItems++;
  }
im用于二进制节点binnode.h的代码为:

  template <typename dataType> class binNode 
 {
 private:
  // private data ====================================
  dataType nodeData;
  binNode<dataType> *left, *right;

        void insert(binNode<dataType>* &root, const dataType& dataItem) 
  {
     if (nodeData == dataItem) 
     {
        throw std::invalid_argument("dataItem already in tree");
     }

     if (dataItem < nodeData) 
     {
        if (left == NULL) 
        {
           left = new binNode(dataItem);
        } 
        else 
        {
           left->insert(left, dataItem);
        }
     } 
     else 
     {
        if (right == NULL) 
        {
           right = new binNode(dataItem);
        } 
        else 
        {
           right->insert(right, dataItem);
        }
     }
     rebalance(root);
  }

thx for Help

问题在于,您在insert中采用的是常量数据类型数据项,但运算符==采用的是非常量M2E参数

您需要将运算符==参数类型指定为常量:


记住const是一个契约:函数承诺不更改其参数的值。所以insert做出了这个承诺,但运算符==没有,所以insert不能让该运算符按原样调用它。通过将const添加到operator==的参数类型中,您可以使operator==做出相同的承诺,这样insert就可以调用它了

实际上我放置了另一个重载运算符>,它也不起作用,除非您使用的是Visual Studio,它可以很好地编译。@stdOrgnlDave-哪个版本?它认为新产品至少在符合标准10和11方面相当不错。这是令人费解的,但BC编译得很好,并在运行时愉快地递归。我相信它也没有表现出正确的行为错误和拒绝在更琐碎的情况下编译,但这是方便的。在链接的代码中,为定义了运算符>,但正在模板中查找运算符运算符重载更改为const(如本问题中所示),它就会工作。或者不用MSVC编译它,它就可以工作了。
bool operator == (const M2E& other) const {
  //...
}