C ++ Hemopurification school exercise 36-- matrix calculation (overloaded operators)
Description Title: a two matrices and b, are two rows and three columns. And the sum of two matrices. Overload operator "+", so that it can be used for adding the matrix. Overload stream insertion operator "<<" and the stream extraction operator ">>", so that it can be used for input and output of the matrix.
#include<iostream>
using namespace std;
class Matrix {
private:
int num[2][3];
public:
friend Matrix operator+(Matrix& m1, Matrix& m2);
friend istream& operator>>(istream& input, Matrix& m);
friend ostream& operator<<(ostream& output, Matrix& m);
};
Matrix operator+(Matrix& m1, Matrix& m2) {
Matrix m3;
for (int i = 0;i < 2;i++) {
for (int j = 0;j < 3;j++) {
m3.num[i][j] = m1.num[i][j] + m2.num[i][j];
}
}
return m3;
}
istream& operator>>(istream& input, Matrix& m) {
for (int i = 0;i < 2;i++) {
for (int j = 0;j < 3;j++) {
input >> m.num[i][j];
}
}
return input;
}
ostream& operator<<(ostream& output, Matrix& m) {
for (int i = 0;i < 2;i++) {
for (int j = 0;j < 3;j++) {
output << m.num[i][j] << " ";
}
cout << endl;
}
return output;
}
int main() {
Matrix m1, m2;
cout << "输入m1:" << endl;
cin >> m1;
cout << "输入m2:" << endl;
cin >> m2;
cout << "m1+m2:" << endl;
Matrix m3 = m1 + m2;
cout << m3;
return 0;
}
Run the test results: