【问题标题】:Creating 2D-Array inside a constuctor in C++在 C++ 的构造函数中创建二维数组
【发布时间】:2015-02-21 18:11:34
【问题描述】:

我正在尝试执行以下操作:

class Test{
private:
    int x;
    int y;
    // Create array[][] here
public:
    Test(const int x, const int y){
        this->x = x;
        this->y = y;
        // set: array[x][y] here
    }
};

如您所见,我想创建一个二维数组,而边界将在构造函数中给出。 我怎样才能做到这一点?

它适用于通常的数组:

class Test{
private:
    int x;
    int y;
    int *array;
public:
    Test(const int x, const int y){
        this->array = new int[x]; // works
        // this->array = new int[x][y] does not work
        this->x = x;
        this->y = y;
    }
};

【问题讨论】:

  • 使用std::vector<std::vector> 代替原始指针
  • 可以使用模板吗?如果您忘记添加释放数组的析构函数,您的示例将会泄漏。
  • 可能值得考虑使用单个 std::vector 而不是 std:vector<:vector>。此外,根据要求,在初始化列表而不是构造函数的主体中实际创建数组可能是一个好主意:Test(const unsigned x, const unsigned y) : x_(x), y_(y), buffer_(x*y) {} 将立即提供具有默认值的有效数组(与未初始化的值相反)。访问元素的算法应该足够简单。

标签: c++ arrays constructor


【解决方案1】:

你应该考虑用指针分配内存,应该如下:

class Test{
private:
    int x;
    int y;
    int **array;
public:
    Test(const int x, const int y){
        int i;
        this->array = new int*[x]; // first level pointer asignation
        for(i=0;i<x;i++){
            this->array[x] = new int[y]; // second level pointer asignation
        }
        // this->array = new int[x][y] does not work
        this->x = x;
        this->y = y;
    }
};

见this。

【讨论】:

    【解决方案2】:

    您可能会遇到here 讨论过的“所有维度必须是常量,除了最左边”的问题。

    请尝试以下方法:

    class Test {
    private:
            int x;
            int y;
            int** myArray;
    public:
    
            Test(const int x, const int y) : x(x), y(y) {
                    myArray = new int*[x];
    
                    for (int firstDimension = 0; firstDimension < x; firstDimension++) {
    
                            myArray[firstDimension] = new int[y];
    
                            for (int secondDimension = 0; secondDimension < y; secondDimension++) {
                                    myArray[firstDimension][secondDimension] = secondDimension;
                            }
                    }
            }
    
            ~Test() {
                    for(int i = 0; i < x; i++)
                            delete[] myArray[i];
                    delete[] myArray;
            }
    };
    

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 1970-01-01
      • 2021-11-13
      • 2022-01-08
      • 2016-07-28
      • 2019-01-09
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      相关资源
      最近更新 更多