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

Its*_*nas 9 c++ stdarray

当我尝试编译我的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;
};
Run Code Online (Sandbox Code Playgroud)

源文件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;
}
Run Code Online (Sandbox Code Playgroud)

有人能告诉我这里有什么问题吗?我发现了类似的主题,但并不是真的相同,我不明白给出的解释.

谢谢.

xcv*_*cvr 13

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

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

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

您可以通过简单地为构造函数定义提供初始化列表来解决此问题.

CubicPatch::CubicPatch(std::array<Point3D, 16> CP)
    : cp(CP)
{}
Run Code Online (Sandbox Code Playgroud)

此外,您可能希望查看此代码.

Point3D::Point3D(float x, float y, float z){
    x = x;
    y = y;
    z = z;
}
Run Code Online (Sandbox Code Playgroud)

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)
{}
Run Code Online (Sandbox Code Playgroud)

  • 当使用`:cp(CP)`时,体内的`cp = CP`是多余的 (3认同)