在构造函数中初始化数组

Jan*_* SE 0 c++ arrays pointers

我想要一个具有成员数组的类.初始化对象时应该给出数组的大小.我刚刚找到了一种方法来指导这样做.我认为它工作正常,但是你可以告诉我这是否是最好的方法,或者有什么东西不起作用我还没有认识到呢?

#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;
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*icz 5

你可以告诉我这是否是最好的方法,或者有什么东西不起作用我还没有认识到?

这是我基于现有最佳实践的考虑因素:

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)
{
}
Run Code Online (Sandbox Code Playgroud)

简而言之,所做的改变:

请注意,当前界面不允许任何访问mesh_points.