从方法返回对象后matrix matrix::operator+(const matrix& right)
,整个数组似乎被删除了!让我们在下面的简化示例中描述这个奇怪的问题:
主.cpp:
#include "matrix.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
matrix a("a.mt");
matrix b("b.mt");
matrix d(a.getRows(),a.getColumns());
d = a+b;
std::cout<<"hooray!";
return 0;
}
矩阵.h:
#ifndef H_MATRIX
#define H_MATRIX
#include <string>
struct field
{
int row;
int column;
double value;
};
class matrix
{
private:
int c; //columns
int r; //rows
field** b; //2d array
void allocmem();
public:
matrix(int rows,int columns);
matrix(std::string filename);
~matrix();
void read(std::string fname);
matrix operator+(const matrix& right);
matrix& operator=(const matrix& right); //deep copy
int getColumns() const;
int getRows() const;
};
#endif
矩阵.cpp
#include "matrix.h"
#include <string>
#include <fstream>
#include <iostream>
void matrix::allocmem()
{
b = new field*[r];
for(int i=0; i < r; i++)
b[i] = new field[c];
}
matrix::matrix(int rows,int columns)
{
c = columns;
r = rows;
allocmem();
}
matrix::matrix(std::string fName)
{
read(fName);
}
matrix::~matrix()
{
for(int i=0; i<r;i++)
delete [] b[i];
delete b;
}
void matrix::read(std::string fname) //load matrix from file
{
std::ifstream is;
is.open(fname);
is>>r>>c; //get matrix dimensions
allocmem();
//go to the first row
char dull = is.peek();
while(dull != '\n'){dull = is.get();}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
is>>b[i][j].value;
b[i][j].row=i+1;
b[i][j].column=j+1;
}
while(dull != '\n'){dull = is.get();}
}
is.close();
}
matrix matrix::operator+(const matrix& right)
{
matrix rMatrix(right.getRows(),right.getColumns());
if((r != right.r) || (c != right.c))
{
return NULL;
}
rMatrix.r = r;
rMatrix.c = c;
//matrix addition algorithm
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
{
rMatrix.b[i][j].value = b[i][j].value+right.b[i][j].value;
rMatrix.b[i][j].row = i+1;
rMatrix.b[i][j].column = j+1;
}
return rMatrix;
}
matrix& matrix::operator=(const matrix& right)
{
if(this == &right)
return *this;
for(int i=0; i<r;i++)
delete [] b[i];
delete b;
r = right.getRows();
c = right.getColumns();
allocmem();
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
{
b[i][j].value = right.b[i][j].value; //RUN-TIME ERROR!
b[i][j].column = j+1;
b[i][j].row = i+1;
}
return *this;
}
int matrix::getColumns() const
{
return c;
}
int matrix::getRows() const
{
return r;
}
吨:
4 4
10.5 20.7 30.5 40.1
0 0 15.4 9.8
4 2 -8.3 4.2
9.3 2.7 1.2 8.9
b.mt:
4 4
-2.5 0.7 30.5 -54.1
0 1 0 9.8
4 7 8.3 4.2
7.3 2.7 -1.2 3.9
这个程序应该从文件中加载两个矩阵,然后计算它们的总和。在实践中,它在深拷贝方法(操作符)内崩溃并=
抛出这样的错误:.
我想问你错误在哪里以及如何修复它。