我是C ++的新手...我正在上几节课-一门针对学生,一门针对课程。课程内部有一个“列表”,用于添加学生对象。
我可以添加一个学生:
void Course::addStudent(Student student)
{
classList.push_back(student);
}
但是当我删除学生时,我无法将其删除。我收到一个关于无法派生Student的错误,以及关于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 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
缺少operator==
所需的std::list::remove
。
#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引用传递,而函数本身为const
。
实时示例:http://ideone.com/xAaMdB
非常感谢Paul!这行得通!我开始着手添加运算符,但随后看到了您的评论。我离我很近,但不完全是。非常感谢您的帮助!谢谢!