回 首 往 昔   更 进 一 步 

Martrix-revolution

段错误

实现一个矩阵乘法,主函数有矩阵类m1,m2,m3,重载 * ,运行结果正确却有段错误,求解 ???

#include<iostream>
#include<iomanip>
using namespace std;

class matrix{
	private:
		int row;
		int column;
		int **mat;
	public:
		matrix(int r=0,int c=0);
		void display();
		~matrix();
		void import();
		friend matrix operator * (matrix &a,matrix &b);
};

matrix::matrix(int r,int c):row(r),column(c){
	if(row==0 || column==0) mat=NULL;
	else {mat=new int *[row]; for(int i=0;i<row;i++) mat[i]=new int[column];}
}
void matrix::import(){
	for(int i=0;i<row;i++)
	for(int j=0;j<column;j++)
	cin>>mat[i][j];
}
void matrix::display(){
	for(int i=0;i<row;i++){
		for(int j=0;j<column;j++){
			cout<<setw(10)<<mat[i][j];
		}
		cout<<endl;
	}
}

matrix operator * (matrix &a,matrix &b){
	matrix c(a.row,b.column);
	if(a.column!=b.row) cout<<"Invalid Matrix multiplication!"<<endl;
	for(int i=0;i<a.row;i++){
		for(int j=0;j<b.column;j++){
			for(int k=0;k<a.column;k++){
				c.mat[i][j] += (a.mat[i][k]*b.mat[k][j]);
			}
		}
	}
	return c;
}

matrix::~matrix(){
	for(int i=0;i<row;i++)
		delete [] mat[i];
	delete [] mat;
}

int main(){
	int r1,c1,r2,c2;
	cin>>r1>>c1;
	matrix m1(r1,c1);
	m1.import();
	cin>>r2>>c2;
	matrix m2(r2,c2);
	m2.import();
	matrix m3(r1,c2);
	m3=m1*m2;
	m3.display();
	return 0;
}

posted on 2018-08-17 22:59  Martrix-revolution  阅读(226)  评论(4编辑  收藏  举报

导航