C++ 操作员'<'的过载不是每次都使用

C++ Overloading of operator '<' is not being used every time

本文关键字:lt 操作员 C++      更新时间:2023-10-16

我有一个person对象,它具有名称、姓氏等属性。我还有3-4个从person类继承的类。

我有另一个类,它将按升序打印所有不同类型的人。因此,我已经重载了运算符'<'我知道它和我在其他地方使用过的一样有效。但由于某种原因,它没有被用于另一个类中的特定方法。

这是我在person类中找到的重载方法。

    bool person::operator< ( const person &p2 ) const
    {    
        if ( surname() < p2.surname() )
           return true;
        else 
        //There are many other conditions which return true or false depending on the attributes.
    }

这是在另一个类(一个子类)中找到的方法,该类应该使用重载运算符,但似乎没有使用它

 vector<person *> contacts::sorted_contacts() const{
    vector<person *> v_contact;
    auto comparison = [] ( person *a, person *b ){  return a < b ;  };  
    //Some code here which fills in the vector
    sort(begin(v_contact), end(v_contact), comparison);
}

这里的排序不起作用。因为,当我使用复制/粘贴重载的实现并将其放在这里时,向量是正确排序的。因为我想重用代码,所以我试图弄清楚为什么这里没有使用运算符<

此处为

auto comparison = [] ( person *a, person *b ){  return a < b ;  }

您正在比较指针,而不是比较对象本身。

为了比较实际对象(这显然是你的意图),你必须取消引用指针。这也是有意义的const合格你的指针正确

auto comparison = [] ( const person *a, const person *b ){  return *a < *b ;  }
auto comparison = [] ( person *a, person *b ){  return a < b ;  }

比较指针,而不是人。

auto comparison = [] ( person *a, person *b ){  return *a < *b ;  }

将比较这些人。