首页 > 解决方案 > 重载返回迭代器和 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;
};

标签: c++

解决方案


重载这些函数的目的是它们的const不同。

考虑:

你传递Class foo;给一个函数

void bar(Class& foo).

如果在此函数中调用findStudent(),则将调用成员函数的非常量版本。结果,您将获得一个std::vector<std::string>. 迭代器将允许分配新值、清除字符串以及对值执行任何其他操作。

现在考虑另一种情况:

void bar(const Class& foo).

在此函数中,findStudents()将调用 const 版本,您将无法修改值。您将能够检查它们、打印它们、对长度求和,也就是说,您将只能对您的学生进行非变异操作。

这样做的目的是启用编译器和 -- 特别重要!-- 程序员对代码进行推理。const 函数不会改变对象的状态,它们保留了代码的不变量。例如,它通常认为,如果您连续两次调用 const 函数,则两次调用都应返回相同的答案。(这“通常”成立,但并非总是如此,尤其是在我们处理硬件时)。


推荐阅读