#include<iostream>
usingnamespacestd;
classMatrix
{
introw;//矩阵的行
intcol;//矩阵的列
int**a;//保存二维数组的元素
public:
Matrix();//默认构造函数
Matrix(intr,intc);
Matrix(constMatrix &is);//拷贝构造函数
voidMadd(constMatrix &is);//矩阵加
Matrix Mmul(constMatrix &is);//矩阵乘
voiddisplay();//显示矩阵元素
};
Matrix::Matrix(intr,intc)
{
row = r;
col = c;
a = (int**)malloc(sizeof(int*)*row);
for(intr = 0; r < row; r++)
{
*(a + r) = (int*)malloc(sizeof(int)*col);
}
printf("请输入数:\n");
for(inti = 0; i < row; i++)
for(intj = 0; j < col; j++)
cin >> a[i][j];
}
Matrix::Matrix(constMatrix & is)
{//拷贝构造函数
row = is.row;
col = is.col;
a =newint*[row];
for(inti = 0; i < row; i++)
{
a[i] =newint[col];
}
a = is.a;
}
voidMatrix::Madd(constMatrix & is)
{
if(row != is.row || col != is.col)//判断两矩阵是否符合相加条件
{
cout <<"相加的矩阵必须行和列一致";
}
else
{
for(inti = 0; i < row; i++)
{
for(intj = 0; j < col; j++)
{
a[i][j] += is.a[i][j];
}
}
}
}
Matrix Matrix::Mmul(constMatrix & is)
{
Matrix M3(this->row, is.col);
if(this->col != is.row)//判断是否符合相乘条件
{
cout <<"不符合两矩阵相乘的条件";
}
else
{
for(inti = 0; i < M3.row; i++)
{
for(intj = 0; j < M3.col; j++)
{
M3.a[i][j] = 0;
for(intn = 0; n < is.row; n++)
{
M3.a[i][j] +=this->a[i][n] * is.a[n][j];
}
}
}
}
returnM3;
}
voidMatrix::display()
{//输出矩阵
for(inti = 0; i < row; i++)
{
for(intj = 0; j < col; j++)
{
cout << a[i][j] <<" ";
}
cout << endl;
}
cout << endl;
}
intmain()
{
Matrix m1(3, 3);
m1.display();
Matrix m2(3, 3);
m2.display();
Matrix m3(3, 2);
m3.display();
cout <<"m1+m2="<< endl;
m1.Madd(m2);
m1.display();
Matrix m4(m1.Mmul(m3));
cout <<"m1*m3="<< endl;
m4.display();
system("pause");
return0;
}
|