删除功能构建失败

时间:2018-11-13 18:06:25

标签: c++

我是C ++的新手,并在我的项目中得到代表餐馆的错误:

error: use of deleted function ‘Dish& Dish::operator=(const Dish&)’
        *__result = *__first;

In file included from /users/studs/bsc/2019/romid/CLionProjects/rest/src/../include/Customer.h:9:0,
                from /users/studs/bsc/2019/romid/CLionProjects/rest/src/../include/Action.h:9,
                from /users/studs/bsc/2019/romid/CLionProjects/rest/src/Action.cpp:1:
/users/studs/bsc/2019/romid/CLionProjects/rest/src/../include/Dish.h:19:7: note: ‘Dish& Dish::operator=(const Dish&)’ is implicitly deleted because the default definition would be ill-formed:
class Dish{
      ^~~~

我不明白是哪个类引起问题或什么是问题。 这是dish.cpp类的一部分。

 #include "../include/Dish.h";
#include <iostream>

Dish::Dish(int d_id, std::string d_name, int d_price, DishType d_type) : 
id(d_id), name(d_name)
price(d_price), type(d_type){}

int Dish::getId() const
 {
    return id;
}

std::string Dish::getName() const {return name;}

int Dish::getPrice() const {return price;}

DishType Dish::getType() const {return type;}

这是dish.h头文件:

#ifndef DISH_H_
#define DISH_H_

#include <string>

enum DishType{
    VEG, SPC, BVG, ALC
};

class Dish{
public:
    Dish(int d_id, std::string d_name, int d_price, DishType d_type);
    int getId() const;
    std::string getName() const;
    int getPrice() const;
    DishType getType() const;
private:
    const int id;
    const std::string name;
    const int price;
    const DishType type;
};


#endif

2 个答案:

答案 0 :(得分:1)

Dish包含诸如const int id;之类的常量成员。因此,将没有可用的自动定义的赋值运算符,因为将一个Dish分配给另一个id也需要为其分配const,但是当然Dish不允许更改值。

因此,在提供用户定义的赋值运算符之前,不允许将一个Dish a(...); Dish b(...); b = a; 分配给另一个。

特别喜欢

export

将触发错误。您正在代码中的某处做类似的事情。

答案 1 :(得分:1)

由于Dish的成员是const,因此编译器无法自动生成赋值运算符,因为它无法更改现有对象的成员。

您可以尝试编写自己的赋值运算符,但是会遇到相同的问题。您需要使成员成为非常量成员,或者停止调用赋值运算符。