gpt4 book ai didi

c++ - 错误 C2280;执行 employees.erase() 时出现 operator =(const Employee &) 问题

转载 作者:行者123 更新时间:2023-11-28 05:45:15 28 4
gpt4 key购买 nike

主题(我的意思是重载运算符默认复制构造函数等)对我来说是新事物,我真的不得到它。我试图避免它,但它还是捕获了我。我有一个容器 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;
};

你不能定义一个 operator= 因为你不能分配一个引用(任务)。去掉引用就万事大吉了(可能慢点,但更安全)

关于c++ - 错误 C2280;执行 employees.erase() 时出现 operator =(const Employee &) 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36359875/

28 4 0