使用构造函数初始化数组 (C++)
Use constructor to initialize array (C++)
如何通过构造函数初始化数组?下面是一个名为 Sort 的类的代码:
private:
double unpartitionedList[];
public:
Sort(double unpartitionedList[]);
Sort::Sort(double unpartitionedList[])
{
this->unpartitionedList = unpartitionedList;
}
我希望能够将数组传递给构造函数并将其存储在 unpartitionedList[]
中。像这样:Sort(array[])
就像现在的代码一样,我在 DevC++ 中收到一个编译器错误:
"[错误] 将'双精度*'赋值为'双精度[0]'时类型不兼容"
我尝试在我认为需要的地方插入引用(&
)和取消引用(*
)运算符,但不幸的是,我的尝试没有成功。
任何建议将不胜感激。
数组不可分配。您必须按元素复制或编写实际的C++代码并使用std::array
或std::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 样式数组的精简包装器(必须在编译时调整大小)。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '