错误 C2280;运算符 =(const Employee &) 在执行 employees.erase() 时出现问题
Error C2280; an issue with operator =(const Employee &) occurs while executing employees.erase()
主题(我的意思是重载运算符、默认和复制构造函数等)对我来说是新的东西,我真的不明白。我试图避免它,但它还是让我明白了。我有一个包含对象的容器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;
};
不能定义运算符=,因为不能分配引用(任务)。删除引用,一切都会好起来(也许更慢,但更安全)
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- C++17中的并行执行策略
- QML按钮点击功能执行顺序
- 程序在执行程序的其余部分之前退出
- 为什么catch中的代码没有被执行
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 将执行、作业和WinAPI相乘
- 对字符数组中的元素执行逐位操作
- 为什么g++在未执行的代码处标记强制转换错误
- 错误 C2280;运算符 =(const Employee &) 在执行 employees.erase() 时出现问题