复制动态二维数组的构造函数

Bra*_*low 2 c++ class copy-constructor

我需要帮助.现在我正在尝试创建一个类Matrix,但每次在Visual Studio 2013中运行它时我的程序都会冻结.我认为复制构造函数存在一些问题.这是整个代码.`

class Matrix
{
private:
    int** matrix;
    int X; // Matrix rows
    int Y; // Matrix columns
public:
    // Default Constructor
    Matrix()
    {
        X = 0;
        Y = 0;
        matrix = NULL;
    }
    // Constructor with parameters
    Matrix(int _X, int _Y)
    {
        srand(time(NULL));

        X = _X;
        Y = _Y;
        matrix = new int*[X];

        for (int i = 0; i < X; i++)
                matrix[i] = new int[Y];

        for (int i = 0; i < X; i++)
        {
            for (int j = 0; j < Y; j++)
            {
                matrix[i][j] = rand() % 100;
            }
        }

    }
    // Copy constructor
    Matrix(const Matrix& N)
    {
        X = N.X;
        Y = N.Y;

        matrix = new int*[X];

        for (int i = 0; i < X; i++)
            matrix[i] = new int[Y];

        for (int i = 0; i < X; i++)
        {
            for (int j = 0; j < Y; j++)
            {
                matrix[i][j] = N.matrix[i][j];
            }
        }
    }
    // Destructor
    ~Matrix()
    {
        for (int i = 0; i < X; i++)
            delete[] matrix[X];
    }
    //--------------------------------------
    void ShowMatrixOnScreen()
    {
        for (int i = 0; i < X; i++)
        {
            for (int j = 0; j < Y; j++)
                cout << matrix[i][j] << "   ";

            cout << endl << endl;
        }
    }
};

void main() 
{
    Matrix x(4, 2);
    x.ShowMatrixOnScreen();
}
Run Code Online (Sandbox Code Playgroud)

`

函数"ShowMatrixOnScreen"在屏幕上打印矩阵"x",然后控制台冻结.

use*_*007 7

你的析构函数有声明 delete[] matrix[X];

matrix[X]不存在,所以你释放了未分配给你的内存,这是未定义的行为.它应该是delete [] matrix[i]!

此外,正如Vlad From Moscow所指出的那样,delete所有内存都是可取的,所以你还应该考虑添加delete [] matrix,删除你分配的1-D指针数组matrix = new int*[X];