用友元函数重载运算符是的二维数组实现相加减

2024-12-25 07:23:39
推荐回答(1个)
回答1:

#include
#define hang 2
#define lie 2
class Matrix
{
private:
int Row;
int Column;
int MATRIX[hang][lie];
public:
Matrix(int r,int c)
{
Row=r;
Column=c;
}
Matrix() {}
void TypeMatrix();
void Print() const;
Matrix& operator = (const Matrix& rhs);
Matrix operator + (const Matrix& rhs);
Matrix operator - (const Matrix& rhs);
};
void Matrix::TypeMatrix()
{
std::cout<<"请输入矩阵:"< for(int i=0;i {
for(int j=0;j {
std::cin>>MATRIX[i][j];
}
}

}
void Matrix::Print() const
{
std::cout<<"矩阵的结果为:"< for(int q=0;q {
for(int s=0;s {

std::cout< if(s==lie-1)
{
std::cout< }
}
}
}

Matrix& Matrix::operator = (const Matrix& rhs)
{
if(this!=&rhs)
{
for(int g=0;g {
for(int h=0;h {
this->MATRIX[g][h]=rhs.MATRIX[g][h];
}
}
}
return *this;
}

Matrix Matrix::operator + (const Matrix& rhs)
{
int i,j;
for(i=0;i {
for(j=0;j {
MATRIX[i][j]=this->MATRIX[i][j]+rhs.MATRIX[i][j];
}
}
return *this ;
}

Matrix Matrix::operator - (const Matrix& rhs)
{

int i,j;
for(i=0;i {
for(j=0;j {
MATRIX[i][j]=this->MATRIX[i][j]-rhs.MATRIX[i][j];
}
}
return *this ;
}

int main()
{
Matrix a,b,c,d;
a.TypeMatrix();
b.TypeMatrix();
c=a+b;
c.Print();

d=a-b;
d.Print();

}