使用构造函数初始化数组 (C++)

Use constructor to initialize array (C++)

本文关键字:C++ 数组 初始化 构造函数      更新时间:2023-10-16

如何通过构造函数初始化数组?下面是一个名为 Sort 的类的代码:

private:
    double unpartitionedList[]; 
public:
    Sort(double unpartitionedList[]);
Sort::Sort(double unpartitionedList[])
{
    this->unpartitionedList = unpartitionedList;
}

我希望能够将数组传递给构造函数并将其存储在 unpartitionedList[] 中。像这样:Sort(array[])

就像现在的代码一样,我在 DevC++ 中收到一个编译器错误:

"[错误] 将'双精度*'赋值为'双精度[0]'时类型不兼容"

我尝试在我认为需要的地方插入引用(&)和取消引用(*)运算符,但不幸的是,我的尝试没有成功。

任何建议将不胜感激。

数组不可分配。您必须按元素复制或编写实际的C++代码并使用std::arraystd::vector

class Sort
{
private:
    double unpartitionedList[]; 
public:
    Sort(double unpartitionedList[]);
};
Sort::Sort(double unpartitionedList[])
{
    this->unpartitionedList = unpartitionedList;
}

该代码不会编译,因为数组不可分配。 您可以通过几种不同的方式实现目标(取决于您未提及的要求)。

方法1:手动内存管理

class Sort
{
private:
    double* unpartitionedList;
    std::size_t _size; 
public:
    Sort(double* upl, std::size_t n);
};
Sort::Sort(double* upl, std::size_t n) : unpartitionedList(upl), _size(n)
{
}

这里有几点需要注意:如果你打算让这个类获得内存的所有权,你必须正确管理它(例如,释放析构函数中的内存,并提供一个适当的复制构造函数来执行深层复制)。 由于内存管理要求,如果不是绝对必要,则不建议使用此方法。

方法 2/3:STD 容器

class Sort
{
private:
    std::vector<double> _upl;
    // or 
    // std::array<double, SIZE> upl; // with a constant SIZE defined
public:
    Sort(const std::vector<double>& upl);
};
Sort::Sort(const std::vector<double>& upl) : _upl(upl)
// Sort::Sort(const std::array<double, SIZE>& upl) : _upl(upl)
{
}

这将消除内存管理要求。 std::vector将允许您在运行时调整数组的大小。 std::array是围绕 C 样式数组的精简包装器(必须在编译时调整大小)。