矩阵相加+重载运算符

程序设计说明:

     有两个均为3行3列的矩阵m1和m2,求两个矩阵之和。重载运算符“+”、“>>”、“<<”,使之能用于矩阵相加、输入和输出。

 

程序代码:

#include<iostream.h>
int i,j;

class Matrix
{
	int matrix[3][3];
public  :
	Matrix ();
	Matrix operator+ (Matrix &m1);
	friend ostream & operator << (ostream &out,Matrix & m);
	friend istream & operator >> (istream &in,Matrix & m);
};

Matrix::Matrix()
{
	for ( i=0;i<3;i++)
		for (j=0;j<3;j++)
			matrix[i][j]=0;
}

Matrix Matrix:: operator+(Matrix &m1)
{
	Matrix tmp;
	for (i=0;i<3;i++)
		for (j=0;j<3;j++)
			tmp.matrix[i][j]=matrix[i][j]+m1.matrix[i][j];
		return tmp;
}

istream & operator>> (istream &in,Matrix &m)
{
	cout <<"请输入矩阵数据:"<< endl;
		for (i=0;i<3;i++)
			for (j=0;j<3;j++)
				in >> m.matrix[i][j];
			return in;
}

ostream & operator<< (ostream &out,Matrix & m)
{
		for (i=0;i<3;i++)
		{
			for (j=0;j<3;j++)
				cout << m.matrix[i][j]<<" ";
			out <<endl;
		}
		return out;
}

void main()
{
	Matrix m1,m2;
	cin >> m1;
	cin >> m2;
	cout << "Matrix m1 :\n" << m1 <<endl;
	cout << "Matrix m2 :\n" << m2 <<endl;
	m1 =m1+m2;
	cout << "Matrix m1+m2=\n" << m1 <<endl;
}

 

 

运行结果:


矩阵相加+重载运算符
 

 

你可能感兴趣的:(J#)