1

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

private:
    double unpartitionedList[]; 

public:
    Sort(double unpartitionedList[]);

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

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

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

“[错误] 将 'double*' 分配给 'double[0]' 时类型不兼容”

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

任何建议将不胜感激。

4

2 回答 2

4

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

于 2013-11-03T22:54:33.797 回答
2
class Sort
{
private:
    double unpartitionedList[]; 

public:
    Sort(double unpartitionedList[]);
};

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

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

方法一:手动内存管理

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 样式数组的薄包装器(并且必须在编译时调整大小)。

于 2013-11-03T23:05:01.297 回答