【问题标题】:Create array with size given in constructor创建具有构造函数中给定大小的数组
【发布时间】:2021-01-02 13:06:52
【问题描述】:

我对 cpp 完全陌生,但知道一些 python。我想创建一个类,它有一个数组作为属性,其大小在构造函数中给出。这是我想做的,但在 python 中:

class test:
    def __init__(self,size):
        self.arr = [x for x in range(size)]

这就是我在 c++ 中所拥有的:

class Field{
public:
    int width;
    int height;
    int field[];
    Field(int _width, int _height){
        width = _width;
        height = _height;
        field = new int[width*height];
    }
};

但是在声明字段的时候我需要提供一个大小,但是这个大小是后面才给出的。我该怎么做?

【问题讨论】:

    标签: c++ arrays class


    【解决方案1】:

    field声明为指针:

    int *field;
    

    在您的构造函数中,您已经对指针进行了动态分配(这与您之前的数组声明有误):

    field = new int[width * height];
    

    不要忘记delete析构函数定义中分配的动态内存。

    通常的建议是使用 C++11 的数组 #include <array> 或向量 (#include <vector>)。

    【讨论】:

      【解决方案2】:

      将字段作为int * 将其指向动态分配的内存。 确保在析构函数中释放它。

      或者

      最好取一个向量并保留等于width * height的内存,如下面的代码所示。

      class Field{
      public:
          int width;
          int height;
          int *field;
          vector<int> v;
          Field(int _width, int _height){
              width = _width;
              height = _height;
              field = new int[width*height];
              v.reserve(width * height);
          }
          ~Field(){
              delete []Field;
          }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-28
        相关资源
        最近更新 更多