【发布时间】:2022-01-06 10:09:16
【问题描述】:
我试图在我的代码中删除员工并将他的薪水改回 0,但我在函数中得到的只是他的 ID。我为集合使用了内置的迭代器,但发现它是 const。我如何使用 mutable 或其他方式将他的薪水更改为 0? 我有一名员工和一名经理——经理可以雇用或解雇该员工,这将改变他的薪水(显然)。 这是我的代码:
class Manager : public Citizen {
protected:
int salary;
std::set<Employee> employees;
void removeEmployee(const int id) {
mutable std::set<Employee>::iterator employee;
for (employee = this->employees.begin(); employee != this->employees.end(); employee++) {
if (employee->getId() == id) {
employee->setSalary(0);
this->employees.erase(employee);
return;
}
}
throw EmployeeNotHired();
}
我遇到的错误-
C:\Users\User\CLionProjects\hw2Cpp\Manager.h:53:50: error: non-member 'employee' cannot be declared 'mutable'
mutable std::set<Employee>::iterator employee;
^~~~~~~~
C:\Users\User\CLionProjects\hw2Cpp\Manager.h:57:42: error: passing 'const mtm::Employee' as 'this' argument discards qualifiers [-fpermissive]
employee->setSalary(0);
我该怎么办?
**** 编辑**** 我尝试将其更改为:
class Employee : public Citizen {
protected:
mutable int salary;
mutable int score;
std::set<Skill> skills;
但我仍然无法将工资更改为 0。
error: passing 'const mtm::Employee' as 'this' argument discards qualifiers [-fpermissive]
employee->setSalary(0);
【问题讨论】:
-
mutable仅适用于成员变量,不适用于局部变量。 -
@Sean 那么在这种情况下我该怎么办?
标签: c++ class error-handling constants