c++ - 如何获取列表的每个对象并调用 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;
}
解决方案
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;
}
推荐阅读
- pandas - 当循环找到特定的字符串序列时创建一个新索引
- android - 在Android Studio中,导入tensorflow lite模型后,生成的示例代码如何使用?
- ios - 在 SwiftUI 中阅读 colorScheme?
- laravel - 在 Laravel 中显示两个不相关的表
- python - 在另一个列表中列出,但第一个列表的元素不需要在第二个列表中一个接一个出现
- java - 尝试在 redisson API 中为 rxjava2 客户端获取排序集中某个范围内的元素计数时出现 ClassCastException
- c++ - 创建一个对象向量,该类包含四个成员,并且能够访问和删除整个对象
- java - 夸库斯 + 派头。处理持久性异常(唯一约束)
- javascript - 调用带有 promise 的控制器函数无法使用 then 函数等待
- javascript - React - “TypeError: undefined is not a function (near '...formFields.map...')”