您正试图将学生与字符串进行比较。这种比较不是默认定义的,所以你必须自己定义一个合适的运算符或者写一些类似(*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;
}
此外,如果学生的名字是私人或受保护的,也没有办法从公共情境访问它,那么你也必须在您的学生定义中添加朋友声明:
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;
}
}
你忘了的东西: 1.一个完整的代码示例。 (例如,studentList从不定义) 2.编译器的实际错误。 –