您正在尝试将 Student 与字符串进行比较。默认情况下未定义此类比较,因此您必须自己定义适当的运算符或编写类似(*it).getName() == studentName 的内容,其中 getName 是 Student 的成员函数,它返回学生的姓名。
此外,您的 for 循环不正确。应该是这样的:
for(auto it = studentList.begin(); it != studentList.end();) {
if((*it).getName() == studentName) {
it = studentList.erase(it);
} else {
++it;
}
}
编辑:如果您决定重载比较运算符,那么这里有一个提示:
bool operator==(const Student& student, const std::string& name) {
return student.getName() == name;
}
bool operator==(const std::string& name, const Student& student) {
return student == name;
}
bool operator!=(const Student& student, const std::string& name) {
return !(student == name);
}
bool operator!=(const std::string& name, const Student& student) {
return !(student == name);
}
对于这个问题,上述四个重载中的第一个就足够了,但通常最好定义几个版本以避免将来出现任何意外。此外,如果 Student 类没有像 getName 这样的成员函数(强烈建议使用这样的函数,除非 Student 是一个所有数据成员都公开的简单结构。)那么你必须更改第一个重载(其余的参考到第一个,所以他们会自动适应变化。)像这样:
bool operator==(const Student& student, const std::string& name) {
return student.name == name;
}
此外,如果 Student 的名称是私有的或受保护的,并且无法从公共上下文中访问它,那么您还必须在 Student 定义中添加一个朋友声明:
class Student {
public:
// Public interface...
private:
std::string name;
friend bool operator==(const Student& student, const std::string& name);
};
友元声明的位置无关紧要,只要它在类的定义中。同样,您只需要将第一个重载设为特权,因为其余重载只调用第一个。
现在可以更改循环:
for(auto it = studentList.begin(); it != studentList.end();) {
if(*it == studentName) {
it = studentList.erase(it);
} else {
++it;
}
}