c++ - 重载返回迭代器和 const_iterator 的成员函数的目的
问题描述
在我的课堂作业中,我想实现预定义类的成员函数。我对这些 findStudent 过载的目的感到困惑。这个类不能设计成只包含一个定义,它返回一个可以转换为 const 的常规迭代器吗?或者更确切地说,使用 std::find 因为它已经被重载以返回一个 const_iterator?
class Class{
public:
Class(std::string name, std::string teacher, std::string capacity);
std::string getTeacher();
std::string getName();
int getCapacity();
void addStudent(std::string);
void removeStudent(std::string);
std::vector<std::string>::iterator findStudent();
std::vector<std::string>::const_iterator findStudent() const;
private:
std::string name;
std::string teacher;
int capacity;
std::vector<std::string> students;
};
解决方案
重载这些函数的目的是它们的const不同。
考虑:
你传递Class foo;
给一个函数
void bar(Class& foo)
.
如果在此函数中调用findStudent()
,则将调用成员函数的非常量版本。结果,您将获得一个std::vector<std::string>
. 迭代器将允许分配新值、清除字符串以及对值执行任何其他操作。
现在考虑另一种情况:
void bar(const Class& foo)
.
在此函数中,findStudents()
将调用 const 版本,您将无法修改值。您将能够检查它们、打印它们、对长度求和,也就是说,您将只能对您的学生进行非变异操作。
这样做的目的是启用编译器和 -- 特别重要!-- 程序员对代码进行推理。const 函数不会改变对象的状态,它们保留了代码的不变量。例如,它通常认为,如果您连续两次调用 const 函数,则两次调用都应返回相同的答案。(这“通常”成立,但并非总是如此,尤其是在我们处理硬件时)。
推荐阅读
- ios - 在 v5 中将预取图像复制到内存 (SDWebImageCacheMemoryOnly)
- ide - 如何在 PhpStorm 中的数组周围保留空白行
- python - 在多张 Excel 中加载数据框的问题
- javascript - 滚动事件侦听器:空的 While 循环,它是如何工作的,为什么?
- android - 无法在 Kotlin Android App 中生成 Dagger 创建的代码
- angular - 当我使用“浏览器刷新/重新加载”或 F5 刷新页面时,拦截器未执行
- python - 如何从多个文件中读取 n 行直到文件结束
- json - 如何使用logstash将json文件中的所有内容发送到elasticsearch
- c# - 迭代异步任务以更新用户角色
- sqlite - 无法用从 sqlite 中的另一个表中获取的几个随机字符串替换一个字符串