我是 C++ 的新手...我正在制作一些类(class) - 一个用于学生,一个用于类(class)。类(class)内部有一个“列表”,可以添加学生对象。
我可以添加学生:
void Course::addStudent(Student student)
{
classList.push_back(student);
}
但是当我去删除一个学生时,我无法删除它。我收到一个关于 Student not be derived 的长错误以及关于 operator==(const allocator) 的错误。
void Course::dropStudent(Student student)
{
classList.remove(student);
}
有什么建议吗? 谢谢!!
我指的是这个网站如何添加/删除元素:http://www.cplusplus.com/reference/list/list/remove/
学生代码:
class Student {
std::string name;
int id;
public:
void setValues(std::string, int);
std::string getName();
};
void Student::setValues(std::string n, int i)
{
name = n;
id = i;
};
std::string Student::getName()
{
return name;
}
完整类(class)代码:
class Course
{
std::string title;
std::list<Student> classList; //This is a List that students can be added to.
std::list<Student>::iterator it;
public:
void setValues(std::string);
void addStudent(Student student);
void dropStudent(Student student);
void printRoster();
};
void Course::setValues(std::string t)
{
title = t;
};
void Course::addStudent(Student student)
{
classList.push_back(student);
}
void Course::dropStudent(Student student)
{
classList.remove(student);
}
void Course::printRoster()
{
for (it=roster.begin(); it!=roster.end(); ++it)
{
std::cout << (*it).getName() << " ";
}
}
最佳答案
正如所指出的,问题是 Student
缺少 std::list::remove
所需的 operator==
>.
#include <string>
class Student {
std::string name;
int id;
public:
bool operator == (const Student& s) const { return name == s.name && id == s.id; }
bool operator != (const Student& s) const { return !operator==(s); }
void setValues(std::string, int);
std::string getName();
Student() : id(0) {}
};
请注意 operator==
和 operator !=
是如何重载的。预计如果两个对象可以用==
进行比较,那么!=
也应该可以使用。检查 operator!=
是如何根据 operator ==
编写的。
另请注意,参数作为常量引用传递,函数本身是const
。
关于c++ - 从 C++ 列表中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378849/