我想删除p1,我重载了==操作符还是没有用
#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;
}
看报错信息啊,左操作数是const,如果你想用成员函数的话,必须成员函数标记为const啊
bool operator==(const Person& p) const
C++对类型的要求比较严格
operator==()
运算符重载函数应该是const
成员函数,改为下面形式
bool operator==(const Person& p) const
{
// ...
}
#include <iostream>
#include <list>
#include <string>
using namespace std;
class Person
{
public:
Person() = delete;
Person(string name,int age, int height)
{
this->m_Age = age;
this->m_Height = height;
this->m_Name = name;
}
bool operator==(const Person& p)
{
bool ret = (this->m_Name == p.m_Name && this->m_Age == p.m_Age && this->m_Height == p.m_Height);
return ret;
}
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 show(list<Person> &L)
{
int idx = 0;
for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
{
cout << "[" << (++idx) <<"] " << "姓名:" << (*it).m_Name << " 年龄:" << it->m_Age << " 身高:" << it->m_Height << endl;
}
}
void test01()
{
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);
list<Person> L;
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);
cout << "排序前" << endl;
show(L);
//排序,按年龄降序
//L.sort();
//不能直接进行排序,要告知排序规则
cout << "排序后" << endl;
L.sort(Compater);
show(L);
cout << "删除后" << endl;
L.remove(p4);
show(L);
}
int main()
{
test01();
return 0;
}
我的测试环境是MSYS2,GCC 11.2,运行结果正常