我有类Employee
和派生类Worker
和Intern
。我将它们存储在vector<shared_ptr<Employee>> Firm;
现在我想通过将vector
中的派生对象Intern
替换为Worker
来将Intern
提升为Worker
,并保存Employee
中的所有字段。
我有:
void Promote(vector<shared_ptr<Employee>>& sourceEmployee) {
auto it = std::find_if(sourceEmployee.begin(), sourceEmployee.end(),
[&sourceEmployee, id](const auto &obj) { return obj->getID() == id; });
if (it != sourceEmployee.end()) {
auto index = std::distance(sourceEmployee.begin(), it);
switch(sourceEmployee[index]->getnum()) { // returning num / recognizing specified class obj
case 0: { // It's Intern, lets make him Worker
auto tmp0 = std::move(*it);
*it = std::make_shared<Worker>(*tmp0); // WORKING now
cout << "Employee " << id << " has been promoted" << endl;
break;
}
class Employee {
//basic c-tors etc.
protected:
int employeeID;
std::string Name;
std::string Surname;
int Salary;
bool Hired;
};
class Intern : public Employee {
protected:
static const int num = 0;
};
class Worker : public Employee {
protected:
static const int num = 1;
};
所以基本上我需要销毁Intern
对象并在同一个地方创建Worker
。
编辑:已解决。我需要制作正确的构造函数并在tmp)
之前添加*
^_^
问题是你Worker
没有一个构造函数接受std::shared_ptr<Employee>
,正如编译器告诉你的那样。
在这一行中:
*it = std::make_shared<Worker>(tmp0);
std::make_shared
将通过调用一个构造函数来构造对象,并将tmp0
作为参数。
旁注:您不必这样做:(*it).reset()
.通过调用上面的std::move
行,您已经重置了共享指针。