Struct+中的C++Struct删除了函数错误

C++ Struct within Struct + deleted function error

本文关键字:函数 错误 删除 中的 C++Struct Struct+      更新时间:2023-10-16

我在一个项目中有一个头文件,我在其中声明了许多结构。后一种结构的某些成员是先前声明的结构的类型。我知道这些成员结构在使用之前必须声明,但我遇到了一种奇怪的行为。

在下面的文件中,我尝试向类型为Coordinate的第二个结构(LUT)添加一个新成员。正如你所看到的,底部结构体libraryEntry有一个类似的成员;这种情况已经持续了一段时间,没有造成任何问题。

#ifndef STRUCTS_H
#define STRUCTS_H
#pragma once
#include <string>
#include "Enums.h"
struct Coordinate {
    int X;
    int Y;
    Coordinate(int x, int y) : X(x), Y(y) {}
};
struct LUT {
    int offset;
    std::string hexCode;
    bool modifiedByTrojan;
    //Coordinate xyCoordinate; <======= Causes build to fail when uncommented
};
struct libraryEntry {
    int id;
    DeviceType deviceType;
    int offSet;
    Coordinate xyCoordinate;
    std::string hexCode;
    DeviceConfiguration deviceConfig;
    libraryEntry(int idNum, DeviceType deviceType, int offSet, Coordinate xyCoordinate, std::string hexCode) :
        id(idNum),
        deviceType(deviceType),
        offSet(offSet),
        xyCoordinate(xyCoordinate),
        hexCode(hexCode)
    {
    }
};
#endif

添加上面的坐标成员会导致错误:

'LUT::LUT(void)':attempting to refernce a deleted function

为什么这只发生在第二个结构中?

在工作的结构(libraryEntry)中,您定义了一个构造函数,并且在构造函数中,您正在使用它的两个arg构造函数初始化xyCoordinate

在编译失败的结构中,您没有定义任何构造函数,因此您获得了默认的无arg构造函数,它使用它们的默认(无arg)构造函数初始化所有内容,包括Coordinate成员。Coordinate没有默认构造函数,因为您声明了一个不同的构造函数,这导致默认构造函数被删除,因此出现错误消息。