gpt4 book ai didi

c++ - "default definition would be ill-formed"是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:59 30 4
gpt4 key购买 nike

我是 C++ 的初学者,我尝试创建一个对象,但遇到错误,而且我不明白哪里出了问题。这是我收到错误时的 hpp 文件 + cpp 文件:

Manager::Manager(const Manager &manager ) :
Worker(manager.name,manager.id,manager.salary){
this->workers=manager.workers;
}

class Manager:public Worker {
private:
std::vector<Worker> workers;
public:
Manager(const char* name, int id, int salary);
Manager(const Manager &manager );
};

错误:

In file included from Manager.hpp:5:0,
from Manager.cpp:1:
Worker.hpp:7:7: note: ‘Worker& Worker::operator=(const Worker&)’ is implicitly deleted because the default definition would be ill-formed:
class Worker{

但是当我这样做时它起作用了:

Manager::Manager(const Manager &manager ) :
Worker(manager.name,manager.id,manager.salary), workers(manager.workers){
}

谁能告诉我为什么?


编辑:

这是 worker 类(Class)的代码:

这是worker.hpp

  class Worker{
protected:
const std::string name;
const int id;
int salary;

public:
Worker(const std::string& name, int id, int salary);
Worker(const Worker& worker );
};

这是 worker.cpp:

#include "Worker.hpp"

Worker::Worker(const std::string &names, int ids, int salarys) :
name(names), id(ids), salary(salarys)
{
}

Worker::Worker(const Worker &worker):
name(worker.name), id(worker.id), salary(worker.salary)
{

}

Worker::~Worker() {

}

std::string Worker::toString(){
std::string s="Worker id:" + id ;
return s;
}

最佳答案

编译器通过对每个字段执行赋值生成的默认赋值运算符。因此,如果其中之一是 const 限定的或不可复制的,编译器将无法发出赋值运算符。 Worker 类(您应该在问题中发布)很可能包含一个或多个此类字段。

请注意,调用 this->workers=manager.workers; 将为存储在 worker 中的每个 Worker 调用复制赋值运算符,同时调用workers(manager.workers) 将调用定义明确的复制构造函数。

关于c++ - "default definition would be ill-formed"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090726/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com