有两个矩阵a和b,均为2行3列int,请重载运算符+、<<、>>。 主程序如下(不能修改): int main() { M a, b, c; cin >> a; cin >> b; c = a + b; cout << c; return 0; }
时间: 2023-06-14 11:02:53 浏览: 45
可以通过以下方式重载运算符、<<和>>:
```cpp
#include <iostream>
using namespace std;
class M {
private:
int mat[2][3];
public:
M() {}
friend istream& operator>>(istream& is, M& m) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
is >> m.mat[i][j];
}
}
return is;
}
friend ostream& operator<<(ostream& os, const M& m) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
os << m.mat[i][j] << " ";
}
os << endl;
}
return os;
}
M operator*(const M& m) const {
M 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;
}
};
int main() {
M a, b, c;
cin >> a;
cin >> b;
c = a * b;
cout << c;
return 0;
}
```
其中,运算符*重载为矩阵元素对应相乘。在<<和>>重载中,使用友元函数访问M类的私有成员mat。