错误C2280;执行employees.erase()时发生operator =(const Employee&)的问题

时间:2016-04-01 15:13:26

标签: c++ oop vector operator-overloading

主题(我的意思是重载运算符默认复制构造函数等)对我来说是新的东西,我真的不喜欢&#39得到它。我试图避免它,但无论如何它已经让我了。我有一个带有对象的容器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,但我甚至不知道如何开始。我已经标明了问题发生的位置。

1 个答案:

答案 0 :(得分:1)

问题在于:

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;
    };

您无法定义运算符=,因为您无法分配引用(任务)。删除引用,它将一切正常(可能更慢,但更安全)