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