gpt4 book ai didi

c++ - 如何在 C++ 中删除这个二维数组

转载 作者:行者123 更新时间:2023-11-30 03:11:31 25 4
gpt4 key购买 nike

我完全不知道为什么我在析构函数中的删除代码无法正常运行。我希望你们能帮助我。

非常感谢!

class Array2D
{
public:
Array2D();
Array2D(int, int);
~Array2D();

private:
int row;
int col;
int **p;
};

Array2D::Array2D()
{
// Default Constructor
}


Array2D::Array2D(int rows, int cols)
{
this -> row = rows;
this -> col = cols;

p = new int* [row];
for(int i=0; i< row; i++)
p[i] = new int[col];

// Fill the 2D array
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
{
p[i][j] = rand () % 100;
}
}


Array2D::~Array2D()
{
// I'm using this way to delete my 2D array.
// however, it won't work!

for (int i = 0; i < row; i++)
{
delete[]p[i];
}
delete[]p;
}

最佳答案

您没有在默认构造函数中初始化任何东西。这意味着析构函数将对默认构造的对象发疯。您也没有禁用复制构造函数,它在您的类中不起作用,因为如果您复制了一个对象,它将尝试删除同一个表两次。例如改成如下

class Array2D
{
public:
Array2D();
Array2D(int, int);
~Array2D();

private:
int row;
int col;
int **p;

void initialize(int rows, int cols);

// disable copy functions (make private so they cannot
// be used from outside).
Array2D(Array2D const&);
Array2D &operator=(Array2D const&);
};

Array2D::Array2D()
{
initialize(0, 0);
}


Array2D::Array2D(int rows, int cols)
{
initialize(rows, cols);
}

void Array2D::initialize(int rows, int cols) {
this -> row = rows;
this -> col = cols;

p = new int* [row];
for(int i=0; i< row; i++)
p[i] = new int[col];

// Fill the 2D array
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
{
p[i][j] = rand () % 100;
}

}

关于c++ - 如何在 C++ 中删除这个二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2216796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com