【问题标题】:C++ - Create a 2D copy constructorC++ - 创建一个 2D 复制构造函数
【发布时间】:2018-05-18 02:27:57
【问题描述】:

我正在努力学习我的期末考试,并尝试将我的动态二维数组复制构造函数放在一起。当我创建备份并打印它以查看它是否有效时,它会一遍又一遍地打印出我相信的相同内存地址。这是我的复制构造函数: 更新,这是我从文件 .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;

我相信我的赋值重载运算符也是正确的,但我发布它只是为了确认它对更聪明的人来说是好的。

【问题讨论】:

  • 数组值本身的复制在哪里?
  • 阅读rule of five。在您的问题中显示minimal reproducible example
  • 好的,我用更多代码更新了这个问题,但我需要知道的主要事情是我的复制构造函数和重载的赋值运算符是否正确。我从中提取数据的文件是温度范围从 1869 年到 2017 年的随机文本文件

标签: c++ multidimensional-array dynamic-arrays


【解决方案1】:

在您的复制构造函数版本中 并复制您只分配的赋值运算符 二维数组的内存,但您不复制原始值 矩阵转换为新矩阵。

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

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;

【讨论】:

  • 我添加了这些行,但它们给了我错误:ClimateChange.exe 中的 0x001E4576 抛出异常:0xC0000005:访问冲突写入位置 0xCDCDCDCD。我在这一行得到了那个错误: Temps[r][c] = original.Temps[r][c];
  • @SmithJohn 错误意味着您正在写入未分配的内存,因此您在创建数组之前添加了这些行。在Temps = new double*[mnumRows]; for (int row = 0; row &lt; mnumRows; row++) Temps[row] = new double[mnumCols]; 之后而不是之前添加这些行。
  • 谢谢,这就是问题所在。真的很感激。
猜你喜欢
  • 2013-04-29
  • 2013-08-04
  • 2017-03-27
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
  • 1970-01-01
相关资源
最近更新 更多