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

29

当我尝试编译我的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;
}

有人能告诉我这里的问题在哪吗?我找到了类似的主题,但并不完全相同,而且我也没理解给出的解释。

谢谢。


13
你认为这行代码 x = x; 是在做什么? - Praetorian
1个回答

37

两件事。类成员在构造函数主体之前初始化,并且默认构造函数是一个没有参数的构造函数。

因为你没有告诉编译器如何初始化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 = x, y = y, z = z没有意义,这是将变量赋值给自身。使用this->x = x 是解决此问题的选项之一,但更符合 C++ 风格的选项是使用初始化列表,如cp 所示。它们允许您在不使用 this->x = x 的情况下为参数和成员使用相同的名称。

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

7
使用cp(CP)时,函数体中的cp = CP是多余的。 - StenSoft
默认构造函数是一个没有参数的构造函数 - 更准确地说,它是一个可以不带参数调用的构造函数。这是有区别的。默认构造函数可以有参数,只要它们有默认值,例如Point3D(float x = 0, float y = 0, float z = 0)就是一个可行的默认构造函数。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接