首页 > 解决方案 > 如何获取列表的每个对象并调用 getName 方法来打印它的名称

问题描述

通过调用名称的 getter 方法来打印列表包含的每个对象的名称时遇到问题。我有班级学生。该类包含一个 Course 类型对象的列表和一个名为 printData() 的方法,其中有一个迭代器来遍历该列表以获取每个 Course 类型对象并为每个对象调用 getCourseName() 方法来打印它的名称。当我构建我的程序时,我收到以下 3 个错误:

1) 'operator=' 不匹配(操作数类型是 'const iterator' {aka 'const std::_List_iterator'} 和 'std::__cxx11::list::const_iterator' {aka 'std::_List_const_iterator'})

2) 传递 'const iterator' {aka 'const std::_List_iterator'} 作为 'this' 参数丢弃限定符

3)'const iterator' {aka 'const struct std::_List_iterator'} 没有名为 'getCourseName' 的成员

有人可以解释我为什么会收到这些错误以及为什么我不能调用 getter 来打印名称吗?谢谢你。

学生班级:

class Sudent
{
    list<Course> courses;
public:
    Student(list<Course> &c);
}

学生类构造函数:

Student::Student(list<Course> &c):
{

    this->courses = c; 
}   

学生类 printData 方法:

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 
    }

}

课程类别:

class Course
{
    string nameOfCourse;

public:
    Course(string n);
    string getCourseName();
};

课程类构造函数:

Course::Course(string n)
{
    nameOfCourse = n;
}

课程 getCourseName 方法:

string Course::getCourseName()
{
    return nameOfCourse;
}

主要的:

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;

}

标签: c++listiterator

解决方案


1) Student::printData() 是 const,所以 courses.begin() 是一个 list::const_iterator 不能分配给非 const 迭代器

2) Course::getCourseName() 不是 const,所以你不能从 const 上下文中调用它。

请看一下这段代码:

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;
}

推荐阅读