我想使用用户输入的关于他们希望更新的变量的输入来更新对象向量数组中的对象变量。
代码是:
class Employee {
public:
std::string empID, empName, empTitle, empHireDate, empSalary;
Employee() {}
// constructor
Employee(string id, string name, string title, string hireDate, string salary) :
empID(id),
empName(name),
empTitle(title),
empHireDate(hireDate),
empSalary(salary)
{}
//returns the employee's ID
string getEmpID() {
return empID;
}
};
(Operator== function, if you saw this project before, you know.)
class employeeMutator : public Employee
void updateEmployee(string input) {
//requests what the user wants to update, and updates it
if (input == "1") {
cout << "what is the new name? ";
string name;
cin >> name;
empName = name;
cout << "updated.";
cout << "\n";
}
(...) repeat and change for other variables. Yes, yes, there is almost certainly a cleaner way to do
this.
}
}
};
int Main() {
vector <Employee> Payroll;
Employee employee;
(insert a few test employees here, they all have different IDs)
string mutate;
cout << "what would you like to update? '1' to update the name, '2' to update the title, '3' to update
the hire date, and '4' to update the salary: ";
cin >> mutate;
//looks for what the user wants to update
for (Employee employee : Payroll) {
if (input == employee.getEmpID()) {
employeeMutator update;
update.updateEmployee(mutate);
}
}
};
代码编译并运行,但是当我使用显示方法时,它显示向量从未更新。
我一直在这个网站和其他网站上查看其他类似的帖子,但没有帮助,他们一直注意到向量可能被复制。到底发生了什么导致更新失败,我该如何修复它?
你的变异者不应该是雇员。从语法的角度考虑一下。负责更改 X 类型记录的任务并不是 X。坦率地说,您的更新不需要从类成员开始。一个免费的功能就可以了。或者
friend
的 Employee
。
此外,您可能想通过引用而不是值来迭代员工。因为否则你会更改临时副本。
最后,在成员名称前加上“emp”前缀以表明它们属于
Employee
是多余的:它们已经是该类的成员。
void updateEmployee(Employee& employee, std::string const& input) {
//requests what the user wants to update, and updates it
if (input == "1") {
std::cout << "what is the new name? " << std::flush;
std::cin >> employee.name;
} else if (input == "2") {
// ...
}
std::cout << "updated." << std::endl;
}
...
for (Employee& employee : payroll) {
if (input == employee.getEmpID()) {
updateEmployee(employee,mutate);
}
}