江南弄 2022-02-07 18:00 采纳率: 77.8%
浏览 26
已结题

c++list容器问题

问题遇到的现象和发生背景

我想删除p1,我重载了==操作符还是没有用

img

img

问题相关代码,请勿粘贴截图
#include<iostream>
using namespace std;
#include<list>
#include<string>
class Person
{
public:
    Person(string name,int age, int height)
    {
        this->m_Age = age;
        this->m_Height = height;
        this->m_Name = name;
    }
    bool operator==(const Person& p)
    {
        if (this->m_Name == p.m_Name && this->m_Age == p.m_Age && this->m_Height == p.m_Height)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    int m_Age;
    string m_Name;
    int m_Height;
};

bool Compater(Person& p1,Person& p2)
{
    if (p1.m_Age == p2.m_Age)
    {
        return p1.m_Height < p2.m_Height;
    }
    return p1.m_Age > p2.m_Age;
}

void test01()
{
    list<Person>L;
    Person p1("孙悟空", 50, 200);
    Person p2("唐僧", 60, 200);
    Person p3("沙悟净", 40, 200);
    Person p4("猪八戒", 80, 200);
    Person p5("关羽", 30, 170);
    Person p6("刘备", 30, 180);
    Person p7("张飞", 30, 175);
    L.push_back(p1);
    L.push_back(p2);
    L.push_back(p3);
    L.push_back(p4);
    L.push_back(p5);
    L.push_back(p6);
    L.push_back(p7);
    //排序,按年龄降序
    //L.sort();
    //不能直接进行排序,要告知排序规则
    L.sort(Compater);
    for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
    {
        cout << "姓名" << (*it).m_Name << " 年龄" << it->m_Age << " 身高" << it->m_Height << endl;
    }

    L.remove(p4);
    cout << "删除后" << endl;
    for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
    {
        cout << "姓名" << (*it).m_Name << " 年龄" << it->m_Age << " 身高" << it->m_Height << endl;
    }
}


int main()
{
    test01();
    return 0;
}


运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
  • 写回答

3条回答 默认 最新

  • [PE]经典八炮 2022-02-07 18:50
    关注

    看报错信息啊,左操作数是const,如果你想用成员函数的话,必须成员函数标记为const啊

    bool operator==(const Person& p) const
    

    C++对类型的要求比较严格

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 2月16日
  • 已采纳回答 2月8日
  • 创建了问题 2月7日

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端