错误 C2280;运算符 =(const Employee &) 在执行 employees.erase() 时出现问题

Error C2280; an issue with operator =(const Employee &) occurs while executing employees.erase()

本文关键字:erase 执行 employees 问题 C2280 运算符 Employee const 错误      更新时间:2023-10-16

主题(我的意思是重载运算符默认复制构造函数等)对我来说是新的东西,我真的不明白。我试图避免它,但它还是让我明白了。我有一个包含对象的容器std::vector<Employee>。甚至认为我不使用= operator

我得到错误:C2280 'Employee &Employee::operator =(const Employee &)': attempting to reference a deleted function

如果我删除线路employees.erase(employees.begin() + 1); ,则错误停止

我发现这是一个常见的问题,但我仍然找不到任何解决方案。请看一下代码:

#include <iostream>
#include <ostream>
#include <string>
#include <vector>
class Employee
{
public:
    std::string name, profession;
    std::string current_task = "NONE";
    int id, age, warrings;
    std::vector<std::string>& tasks;
    Employee::Employee(std::vector<std::string>& tasks) : tasks(tasks)
    {
        warrings = 0;
    };
    virtual void AssignNewTask(std::string input_string)
    {
        for (unsigned int i = 0; i < tasks.size(); i++)
        {
            if (input_string == tasks[i])
            {
                current_task = input_string;
                std::cout << ">> Przydzielony nowy task!" << std::endl;
                return;
            }
        }
        std::cout << input_string << "nie nalezy do listy obowiazkow " << profession << std::endl;
    }
};
class HR : public Employee
{
private:
    static std::vector<std::string> tasks;
public:
    HR::HR() : Employee(tasks)
    {
        Employee::profession = "HR Specialist";
    }
};
class Helpdesk : public Employee
{
private:
    static std::vector<std::string> tasks;
public:
    Helpdesk::Helpdesk() : Employee(tasks)
    {
        Employee::profession = "Helpdesk Technician";
    }
};
std::vector<std::string> HR::tasks = { "HR task" };
std::vector<std::string> Helpdesk::tasks = { "Helpdesk task" };
bool operator==(const Employee & obj, const std::string & std)
{
    if ((obj.name == std) || (std == obj.name))
    {
        return true;
    }
    else
    {
        return false;
    }
}
int main()
{
    std::vector<Employee> employees;
    std::cout << "Welcome message" << std::endl;
    // it works
    employees.push_back(HR());
    employees.push_back(Helpdesk());
    // it also works
    employees.pop_back();
    employees.push_back(Helpdesk());
    // the issue occurs !
    employees.erase(employees.begin() + 1);
    system("pause");
}

我想我应该重载= operator,但我甚至不知道如何开始。我已经标记了问题发生的位置。

问题就在这里:

class Employee
{
public:
    std::string name, profession;
    std::string current_task = "NONE";
    int id, age, warrings;
    std::vector<std::string> *tasks; // <=== use a pointer
    Employee(std::vector<std::string>& tasks) : tasks(&tasks)
    {
        warrings = 0;
    };

不能定义运算符=,因为不能分配引用(任务)。删除引用,一切都会好起来(也许更慢,但更安全)