在构造函数中初始化数组
initialize array in constructor
我想要一个具有成员数组的类。当我初始化对象时,应该给出数组的大小。我刚刚找到了一种带有指针的方法。我认为它工作正常,但你能告诉我这是否是最好的方法,或者是否有任何我还没有认识到的东西不起作用?
#include <iostream>
using namespace std;
class Surface {
private:
float dx;
int N;
float* mesh_points;
public:
Surface(float, int);
~Surface();
void set_dx (float);
float get_dx();
};
Surface::Surface(float dx,int N){
this->dx = dx;
this ->N = N;
mesh_points = new float[N];
}
void Surface::set_dx (float dx) {
this->dx = dx;
}
float Surface::get_dx (void) {
return dx;
}
Surface::~Surface(){
delete[] mesh_points;
}
int main () {
Surface s(1.2,10);
s.set_dx (3.3);
cout << "dx: "<< s.get_dx() <<endl;
float mesh_points[3];
return 0;
}
你能告诉我这是否是最好的方法,或者是否有任何我还没有认识到的东西不起作用?
这是我基于现有最佳实践的看法:
class Surface {
private:
std::vector<float> mesh_points;
public:
float dx;
Surface(float dx, std::size_t n);
};
Surface::Surface(float dx, std::size_t n)
: dx(dx)
, mesh_points(n)
{
}
简而言之,所做的更改:
- 摆脱了手动内存管理,这也意味着 dtor。
- 在声明中添加了参数的名称(对于可用性/IDE 非常重要,不要删除它们!
- 摆脱了多余的访问器并公开
dx
。 - 使用了 ctor 初始化列表,使正文过时。
- 摆脱了
using namespace std;
代替显式std::
前缀。 - 将
n
类型更改为std::size_t
(请参阅注释(。
请注意,当前界面不允许任何访问mesh_points
。
这是一个替代建议,它允许您保留当前的实现,但更安全。
class Surface {
private:
float dx;
int N;
float* mesh_points;
public:
Surface(float, int);
~Surface();
void set_dx (float);
float get_dx();
Surface(const Surface&) = delete; // new
Surface& operator=(const Surface&) = delete; // new
};
通过删除复制构造函数和复制赋值运算符的实现,可以防止复制Surface
对象(无论如何,这都可能导致程序崩溃(。现在,任何复制Surface
对象的尝试都将导致编译时错误。
只是一个建议,我的第一选择永远是使用std::vector
.
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- 当 std 数组初始化太小时,C++会引发错误吗?
- 如何确定结构数组初始化的大小?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 此代码中的数组初始化样式是什么?这是标准的吗?
- C++ 使用数组初始化时的 STL 向量内存管理