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

Replacing object in vector of derived objects "no matching function to call"

我有 class Employee 并导出 class 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 行,您已经重置了共享指针。