64,678
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
class My_Matrix
{
int Rows;
int Cols;
double **matrix_num;
void del();
public:
My_Matrix(const double *_matrix,int row,int col); //从double 到 MyMatrix的构造函数
My_Matrix(const My_Matrix &);
My_Matrix & operator=(const My_Matrix &);
~My_Matrix();
My_Matrix& operator +=(const My_Matrix&);
My_Matrix& operator -=(const My_Matrix&);
friend std::ostream& operator<<(std::ostream& out,const My_Matrix& _matrix);
};
void My_Matrix::del()
{
if(matrix_num !=0)
{
for(int i=0;i<Rows;++i)
delete []matrix_num[i];
delete []matrix_num;
matrix_num=0;
}
}
My_Matrix::My_Matrix(const double *_matrix,int row,int col)
{
Rows=row;
Cols=col;
matrix_num=new double *[Rows];
for(int i=0;i<Rows;++i)
{
matrix_num[i]=new double[Cols];
for(int j=0;j<Cols;++j)
matrix_num[i][j]=_matrix[i*Cols+j];
}
}
My_Matrix::My_Matrix(const My_Matrix &_matrix)
{
Rows=_matrix.Rows;
Cols=_matrix.Cols;
matrix_num=new double*[_matrix.Rows];
for(int i=0;i<_matrix.Rows;++i)
{
matrix_num[i]=new double[_matrix.Cols];
for(int j=0;j<_matrix.Cols;++j)
matrix_num[i][j]=_matrix.matrix_num[i][j];
}
}
My_Matrix& My_Matrix::operator=(const My_Matrix& _matrix)
{
del();
Rows=_matrix.Rows;
Cols=_matrix.Cols;
matrix_num=new double*[_matrix.Rows];
for(int i=0;i<_matrix.Rows;++i)
{
matrix_num[i]=new double[_matrix.Cols];
for(int j=0;j<_matrix.Cols;++j)
matrix_num[i][j]=_matrix.matrix_num[i][j];
}
return *this;
}
My_Matrix::~My_Matrix()
{
del();
}
My_Matrix& My_Matrix::operator+=(const My_Matrix& _matrix)
{
if(Rows!=_matrix.Rows || Cols!=_matrix.Cols)
throw std::runtime_error("ERROR DATA!!");
for(int i=0;i<Rows;++i)
{
for(int j=0;j<Cols;++j)
matrix_num[i][j]+=_matrix.matrix_num[i][j];
}
return *this;
}
My_Matrix& My_Matrix::operator-=(const My_Matrix& _matrix)
{
if(Rows!=_matrix.Rows || Cols!=_matrix.Cols)
throw std::runtime_error("ERROR DATA!!");
for(int i=0;i<Rows;++i)
{
for(int j=0;j<Cols;++j)
matrix_num[i][j]-=_matrix.matrix_num[i][j];
}
return *this;
}
std::ostream& operator<<(std::ostream& out,const My_Matrix& _matrix)
{
for(int i=0;i<_matrix.Rows;++i)
{
out.setf(std::ios::left);
out.precision(6);
for(int j=0;j<_matrix.Cols;++j)
{
out.width(10);
out<<_matrix.matrix_num[i][j];
}
out<<std::endl;
}
return out;
}
My_Matrix operator+(const My_Matrix& _matrix1,const My_Matrix& _matrix2)
{
My_Matrix temp(_matrix1);
return temp+=_matrix2;
}
My_Matrix operator-(const My_Matrix& _matrix1,const My_Matrix& _matrix2)
{
My_Matrix temp(_matrix1);
return temp-=_matrix2;
}
int main()
{
double x[3][3]=
{
{1,2,3},
{2,1,1},
{2,3,1}
};
My_Matrix _matrix((double*)x,3,3);
std::cout<<_matrix<<std::endl;
My_Matrix _other(_matrix);
std::cout<<_other<<std::endl;
My_Matrix m=_other+_matrix;
std::cout<<m<<std::endl;
m=m-_other;
std::cout<<m<<std::endl;
return 0;
}