调用隐式删除的默认构造函数

Call to implicitly-deleted default constructor

本文关键字:默认 构造函数 删除 调用      更新时间:2023-10-16

当我试图编译C++项目时,我得到错误消息调用隐式删除的'std::array'默认构造函数。

头文件cubic_patch.hpp

#include <array>
class Point3D{
public:
    Point3D(float, float, float);
private:
    float x,y,z;
};
class CubicPatch{
public:
    CubicPatch(std::array<Point3D, 16>);
    std::array<CubicPatch*, 2> LeftRightSplit(float, float);
    std::array<Point3D, 16> cp;
    CubicPatch *up, *right, *down, *left;
};

源文件cubic_patch.cpp

#include "cubic_patch.hpp"
Point3D::Point3D(float x, float y, float z){
    x = x;
    y = y;
    z = z;
}
CubicPatch::CubicPatch(std::array<Point3D, 16> CP){// **Call to implicitly-deleted default constructor of 'std::arraw<Point3D, 16>'**
    cp = CP;
}
std::array<CubicPatch*, 2> CubicPatch::LeftRightSplit(float tLeft, float tRight){
    std::array<CubicPatch*, 2> newpatch;
    /* No code for now. */
    return newpatch;
}

有人能告诉我这里出了什么问题吗?我发现了相似的话题,但并不完全相同,我不理解给出的解释。

谢谢。

两件事。类成员在构造函数的主体之前初始化,默认构造函数是不带参数的构造函数。

因为您没有告诉编译器如何初始化cp,所以它尝试调用std::array<Point3D, 16>的默认构造函数,但没有,因为Point3D没有默认构造函数。

CubicPatch::CubicPatch(std::array<Point3D, 16> CP)
    // cp is attempted to be initialized here!
{
    cp = CP;
}

您可以通过简单地提供一个带有构造函数定义的初始值设定项列表来解决这个问题。

CubicPatch::CubicPatch(std::array<Point3D, 16> CP)
    : cp(CP)
{}

此外,您可能还想了解一下这段代码。

Point3D::Point3D(float x, float y, float z){
    x = x;
    y = y;
    z = z;
}

x = xy = yz = z没有意义。您正在为变量本身赋值。this->x = x是解决这一问题的一个选项,但一个更具c++风格的选项是像cp一样使用初始值设定项列表。它们允许您在不使用this->x = x 的情况下对参数和成员使用相同的名称

Point3D::Point3D(float x, float y, float z)
    : x(x)
    , y(y)
    , z(z)
{}