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

 台湾金门高粱酒业集团股份公司 发布于 2023-02-13 10:17

我有一个人物对象,其名称,姓氏等属性......我还有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.
    }

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

 vector contacts::sorted_contacts() const{

    vector 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);
}

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

1 个回答
  • 这里

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

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

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

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

    2023-02-13 10:19 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有