Reputation: 529
I have a problem with printing the name of each object that a list contains by calling the getter method for the name. I have the class Student. That class contains a list of Course type objects and a method called printData(), that inside has an iterator to loop through the list to get each Course type object and call for each object the getCourseName() method to print it's name. When I build my programm I get the followin 3 errors:
1) no match for 'operator=' (operand types are 'const iterator' {aka 'const std::_List_iterator'} and 'std::__cxx11::list::const_iterator' {aka 'std::_List_const_iterator'})
2) passing 'const iterator' {aka 'const std::_List_iterator'} as 'this' argument discards qualifiers
3)'const iterator' {aka 'const struct std::_List_iterator'} has no member named 'getCourseName'
Can someone explain me why I get these errors and why I can't call the getter to print the name?. Thank you.
Student class:
class Sudent
{
list<Course> courses;
public:
Student(list<Course> &c);
}
Student class constructor:
Student::Student(list<Course> &c):
{
this->courses = c;
}
Student class printData method:
void Student::printData() const
{
list<Course>::iterator it;
for(it = courses.begin(); it != courses.end(); it++)
{
cout << *it.getCourseName(); //It doesn't show me the option to choose from methods of Course class
}
}
Course class:
class Course
{
string nameOfCourse;
public:
Course(string n);
string getCourseName();
};
Course class constructor:
Course::Course(string n)
{
nameOfCourse = n;
}
Course getCourseName method:
string Course::getCourseName()
{
return nameOfCourse;
}
Main:
int main()
{
Course c1("Math");
Course c2("Algebra");
Course c3("Geometry");
Course arr[3] = {c1, c2, c3};
list<Course> course_param;
for(int i = 0; i < 3; i++)
{
course_param.push_back(arr[i]);
}
Student stud1(course_param);
stud1.printData(); //I want to print the names of student's courses;
}
Upvotes: 0
Views: 139
Reputation: 556
1) Student::printData() is const, so courses.begin() is a list::const_iterator which can't be assigned to a non-const iterator
2) Course::getCourseName() is not const, so you can't call it from const context.
Please take a look at this code:
class Course {
public:
Course(const string& n) : nameOfCourse(n) {}
const string& getCourseName() const noexcept { return nameOfCourse; }
private:
string nameOfCourse;
};
class Student {
public:
Student(list<Course> c) : courses(std::move(c)) {}
void printData() const noexcept {
for (const auto& course : courses) {
cout << course.getCourseName() << "\n";
}
}
private:
list<Course> courses;
};
int main() {
Student stud1({ Course("Math"), Course("Algebra"), Course("Geometry") });
stud1.printData(); //I want to print the names of student's courses;
}
Upvotes: 1