结构的初始化

Initialization of the structure

本文关键字:初始化 结构      更新时间:2023-10-16

在我的程序中我有结构:

struct point {
  float x;
  float y;
};

编辑:我需要创建

   struct Path{
   Point array[];
}

用函数init_path(Path *p, int size)初始化它。
我的问题是,如何定义功能?预先感谢。

您的Path可能是:

struct Path {
    point* points;
};
void init_path(Path *path, int size) {
    path->points = new point[size]();
}

但是,为什么您的教授想要一个功能而不是适当的构造函数/破坏者仍然是一个谜。在这里,您仍然需要在某个地方的points上调用delete[]。使用以下结构,您不需要任何init功能,并且对象将正确删除其资源。

struct Path {
    Path(unsigned size) : points{ new point[size] } {}
    ~Path() { delete[] points; }
    point* points;
};