替换派生对象向量中的对象"no matching function to call"



我有类Employee和派生类WorkerIntern。我将它们存储在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行,您已经重置了共享指针。

最新更新