资讯动态

用const重载解决成员函数的调用错误

发布时间:2026/10/28 2:04:21 来源:尧图企业网站定制
从截图中可以很明显看到在showStudentByID(...) const中调用findStudentByID(...)这个成员函数时报错了这个bug的根本原因是在showStudentByID(...) const 内隐式的this是指向const对象指针但是在findStudentByID(...) 函数内部没有const的限定理论上可能修改对象因此不能通过const 对象调用#pragma once #include iostream #include vector #include string #includeStudent.h class StudentManager { private: std::vectorStudent stu; public: void addStudent(const Student s); void showALL() const; Student *findStudentByID(int ID); //*按学号查找学生 void showStudentByID(int id) const; //*按学号删除学生 bool removeStudentByID(int id); bool ReviseGrade(int id, int final); };也许我们会遇到这样一个应用的场景某个函数我既要在常态成员函数里面去调用又要在非常态的成员函数里面去调用怎么进行解决呢当然最简单的就是把const函数的const给去了这个毋庸置疑但是我学习了一个工程上的写法之前从来没听过的的就是给这个成员函数增加一个const限定重载const-qualified-overload第二个版本返回const Student* 也不是偶然const对象中的学生也不应该通过返回值被修改Student *StudentManager::findStudentByID(int ID) { for (Student s : stu) { if (s.getID() ID) { return s; } } return nullptr; } const Student *StudentManager::findStudentByID(int ID) const { for (const Student s : stu) // 加上 const { if (s.getID() ID) { return s; } } return nullptr; }当然需要现在头文件里面去写声明这个就是一种比较好的解决办法编译器会自动识别的这样就可以做到类中某一个成员函数在改成常态成员函数之后如何避免编译报错的问题void StudentManager::showStudentByID(int id) const { const Student* student findStudentByID(id); if (student nullptr) { std::cout Student not found\n; return; } student-display(); }本次结论const成员函数只能调用其他const成员函数需要同时支持修改和只读访问的时候可以提供const/non-const两个重载

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑