# C++习题 矩阵求和--重载运算符

C++习题 矩阵求和--重载运算符

``````1 2 3
4 5 6

7 8 9
1 2 3
``````

``````8 10 12
5 7 9
``````

``````#include<stdio.h>
int main()
{
float a,b,c,d,m,n,e,f,g,h,i,j;
scanf("%f %f %f",&a,&b,&c);
scanf("%f %f %f",&d,&m,&n);
scanf("%f %f %f",&e,&f,&g);
scanf("%f %f %f",&h,&i,&j);
printf("%.0f %.0f %.0f\n",a+e,b+f,c+g);
printf("%.0f %.0f %.0f\n",d+h,m+i,n+j);
}``````

``````
#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix();
friend Matrix operator+(Matrix &,Matrix &);
friend ostream& operator<<(ostream&,Matrix&);
friend istream& operator>>(istream&,Matrix&);
private:
int mat[2][3];
};
Matrix::Matrix()
{
}
Matrix operator+(Matrix &a,Matrix &b)
{
Matrix m;
for(int i=0;i<2;i++)
for(int j=0;j<3;j++){
m.mat[i][j]=a.mat[i][j]+b.mat[i][j];
}
return m;
}
ostream& operator<<(ostream& output,Matrix& m)
{
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
output<<m.mat[i][j]<<' ';
}
output<<endl;
}
return output;
}
istream& operator>>(istream&input,Matrix&m)
{
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
input>>m.mat[i][j];
return input;
}
int main()
{
Matrix a,b,c;
cin>>a;
cin>>b;
c=a+b;
cout<<c<<endl;
return 0;
}
``````