C++每次都没有使用运算符'<'的重载

mok*_*211 3 c++ overloading vector operator-overloading

我有一个人物对象,其名称,姓氏等属性......我还有3-4个类继承自人类.

我有另一个类,它将按升序打印所有不同类型的人.所以,我已经重载了运算符'<',我知道它的工作方式与我在其他地方使用它一样.但由于某种原因,它并没有被用于这个不同类别的特定方法.

这是我在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.
    }
Run Code Online (Sandbox Code Playgroud)

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

 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);
}
Run Code Online (Sandbox Code Playgroud)

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

AnT*_*AnT 9

这里

auto comparison = [] ( person *a, person *b ){  return a < b ;  }
Run Code Online (Sandbox Code Playgroud)

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

为了比较实际对象(显然是你的意图),你必须取消引用指针.正确地对你的指针进行const限定也是有意义的

auto comparison = [] ( const person *a, const person *b ){  return *a < *b ;  }
Run Code Online (Sandbox Code Playgroud)