有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加。如:c = a+b。
时间: 2024-05-06 10:20:25 浏览: 93
C++代码如下:
```cpp
#include <iostream>
using namespace std;
class Matrix {
private:
int mat[2][3];
public:
Matrix() {}
// 重载运算符+
Matrix operator+(const Matrix &m) const {
Matrix res;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
res.mat[i][j] = mat[i][j] + m.mat[i][j];
}
}
return res;
}
// 重载运算符<<
friend ostream& operator<<(ostream &os, const Matrix &m) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
os << m.mat[i][j] << " ";
}
os << endl;
}
return os;
}
// 重载运算符>>
friend istream& operator>>(istream &is, Matrix &m) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
is >> m.mat[i][j];
}
}
return is;
}
};
int main() {
Matrix a, b, c;
cout << "请输入矩阵a:" << endl;
cin >> a;
cout << "请输入矩阵b:" << endl;
cin >> b;
c = a + b;
cout << "a + b = " << endl;
cout << c;
return 0;
}
```
运行截图:
![运行截图](matrix.png)
阅读全文