题目描述
有两个矩阵a和b均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加。
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
class Matrix{
public:
Matrix();
friend Matrix operator+ (Matrix &,Matrix &);
void input();
void display();
private:
int mat[2][3];
};
int main(){
Matrix a,b,c;
a.input();
b.input();
cout<<"\n"<<"Matrix a:"<<"\n";
a.display();
cout<<"\n"<<"Matrix b:"<<"\n";
b.display();
c = a + b;
cout<<"\n"<<"Matrix c = Matrix a + Matrix b:"<<"\n";
c.display();
return 0;
}
Matrix::Matrix(){
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
mat[i][j] = 0;
}
}
}
void Matrix::input(){
cout<<"input value of matrix:"<<"\n";
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
cin>>mat[i][j];
}
}
}
void Matrix::display(){
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
cout<<mat[i][j]<<" ";
}
cout<<"\n";
}
}
Matrix operator+(Matrix &a,Matrix &b){
Matrix c;
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c.mat[i][j] = a.mat[i][j] + b.mat[i][j];
}
}
return c;
}