在构造函数中初始化数组

initialize array in constructor

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

我想要一个具有成员数组的类。当我初始化对象时,应该给出数组的大小。我刚刚找到了一种带有指针的方法。我认为它工作正常,但你能告诉我这是否是最好的方法,或者是否有任何我还没有认识到的东西不起作用?

#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.