在构造函数中初始化数组

时间:2018-09-17 10:07:33

标签: 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;
}

2 个答案:

答案 0 :(得分: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)
{
}

简而言之,所做的更改:

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

答案 1 :(得分:0)

这是另一种建议,可以让您保留当前的实现,但要安全得多。

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

相关问题