c++实现矩阵乘法出现问题,神马情况
#include<iostream>using namespace std;
class Matrix
{
private:
int *m;
int row;
int col;
public:
Matrix();
Matrix(int r,int c);
Matrix operator + (Matrix &m1);
Matrix operator - (Matrix &m1);
Matrix operator * (Matrix &m1);
//Matrix & operator = (Matrix &m1);
//Matrix & operator += (Matrix &m1);
void print();
};
Matrix::Matrix()
{
}
Matrix::Matrix(int r,int c)
{
row=r;
col=c;
m=new int[row*col];
int i;
for(i=0;i<row*col;i++)
m[i]=i;
}
Matrix Matrix::operator + (Matrix &m1)
{
Matrix matrix;
int i,j;
int rowmin=(row<=m1.row?row:m1.row);
int colmin=(col<=m1.col?col:m1.col);
matrix.row =rowmin;
matrix.col = colmin;
matrix.m = new int[rowmin*colmin];
for(i=0;i<rowmin;i++)
for(j=0;j<colmin;j++)
matrix.m[i*colmin+j]=m[i*col+j]+m1.m[i*m1.col+j];
return matrix;
}
Matrix Matrix::operator - (Matrix &m1)
{
Matrix matrix;
int i,j;
int rowmin=(row<=m1.row?row:m1.row);
int colmin=(col<=m1.col?col:m1.col);
matrix.row = rowmin;
matrix.col = colmin;
matrix.m = new int[rowmin*colmin];
//Matrix matrix(rowmin,colmin);
for(i=0;i<rowmin;i++)
for(j=0;j<colmin;j++)
matrix.m[i*colmin+j]=m[i*col+j]-m1.m[i*m1.col+j];
return matrix;
}
Matrix Matrix::operator * (Matrix &b)
{
Matrix c;
if(col != b.row){
cout<<"不能相乘!"<<endl;
exit(0);
}
c.row = row;
c.col =b.col;
c.m = new int[row*b.col];
int i,j,k;
for(i=0;i<row;i++)
for(j=0;j<b.col;j++)
{
c.m[i*b.col+j]=0;
for(k=0;k<b.col;k++)
c.m[i*b.col+j]+=(m[i*col+k])*(b.m[k*b.col+j]);//方阵的乘法结果正确,但是不是方阵结果不对!!
}
return c;
}
/*
Matrix & Matrix::operator = (Matrix &m1)
{
int i,j;
for(i=0;i<m1.row;i++)
for(j=0;j<m1.col;j++)
m[i*col+j]=m1.m[i*col+j];
return *this;
}
Matrix & Matrix::operator += (Matrix &m1)
{
int i,j;
for(i=0;i<m1.row;i++)
for(j=0;j<m1.col;j++)
m[i*col+j]=m[i*col+j]+m1.m[i*col+j];
return *this;
}
*/
void Matrix::print()
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
cout<<m[i*col+j]<<"\t";
cout<<endl;
}
}
//#include<iostream>
//#include"head.h"
//using namespace std;
int main()
{
Matrix A1(3,2),A2(2,3),A3,A4,A5;
A3=A1+A2;
A4=A1-A2;
//A5=A1*A2;
cout<<"A1="<<endl;
A1.print();
cout<<"A2="<<endl;
A2.print();
cout<<"A3="<<endl;
A3.print();
cout<<"A4="<<endl;
A4.print();
cout<<"A5="<<endl;
A5=A1*A2;
A5.print();
//Matrix A6(3,2);
//A6=A1;
//cout<<"A6="<<endl;
//A6.print();
//A2+=A1;
//cout<<"A2="<<endl;
//A2.print();
return 0;
}
加减运算没有问题,乘法运算有问题!!!