C++ - 创建二维复制构造函数

C++ - Create a 2D copy constructor

我正在努力学习我的期末考试,我试着把我的动态二维数组复制构造函数放在一起。当我创建备份并打印它以查看它是否有效时,它一遍又一遍地打印出我认为相同的内存地址。这是我的复制构造函数: 更新,这里是我从文件 .txt

中读取数据的地方
void Matrix::readTemps(ifstream &inFile) 
{
    while (!inFile.eof())
    {
        for (int row = 0; row < mnumRows; row++)
        {
            for (int col = 0; col < mnumCols; col++)
            {
                inFile >> Temps[row][col];
            }
        }
    }
}
Matrix::Matrix(const Matrix & original) 
{
    mnumRows = original.mnumRows;
    mnumCols = original.mnumCols;
    Temps = new double*[mnumRows];
    for (int row = 0; row < mnumRows; row++) 
        Temps[row] = new double[mnumCols];
}

Matrix& Matrix::operator=(const Matrix & second)  
{  
    if (this != &second)
    {
        delete[] Temps;
        mnumRows = second.mnumRows;
        mnumCols = second.mnumCols;
        Temps = new double*[second.mnumRows];
        for (int row = 0; row < mnumRows; row++)
            Temps[row] = new double[mnumCols];
    }
    return *this;
}

更新,这是在我的 main.cpp:

//Example of overloaded assignment operator.
Matrix TestMatrix;
TestMatrix = NYCTemps;

//Example of copy constructor.
Matrix copyOfMatrix(NYCTemps); // The traditional way to copy the phonebook.

NYCTemps.display();
copyOfMatrix.display();
cout << endl;

我相信我的赋值重载运算符也是正确的,但我发布它只是为了从更聪明的头脑中确认它是好的。

在你的拷贝构造函数中 和复制赋值运算符你只分配 二维数组的内存,但您不复制原始值 矩阵到新矩阵。

您应该在两种方法中添加这些行

for (int r = 0; r < mnumRows; ++r)
    for (int c = 0; c < mnumCols; ++c)
        Temps[r][c] = original.Temps[r][c];  // or second.Temps[r][c]

Temps 是二维数组,所以在复制赋值运算符中 它必须被删除(首先删除为每行中的列分配的内存,然后删除行的内存)

for (int r = 0; r < mnumRows; ++r)
    delete[] Temps[r];
delete[] Temps;