【发布时间】: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