【问题标题】:How can I get every object of a list and call the getName method to print it's name如何获取列表的每个对象并调用 getName 方法来打印它的名称
【发布时间】:2020-09-27 11:11:46
【问题描述】:

通过调用名称的 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++ list iterator


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      相关资源
      最近更新 更多