有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加。
时间: 2024-05-08 08:20:57 浏览: 92
可以通过重载运算符“+”来实现矩阵相加。具体实现如下:
```cpp
#include <iostream>
using namespace std;
class Matrix {
private:
int a[2][3];
public:
Matrix() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = 0;
}
}
}
Matrix operator+(const Matrix& other) {
Matrix result;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
result.a[i][j] = a[i][j] + other.a[i][j];
}
}
return result;
}
friend istream& operator>>(istream& in, Matrix& m) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
in >> m.a[i][j];
}
}
return in;
}
friend ostream& operator<<(ostream& out, const Matrix& m) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
out << m.a[i][j] << " ";
}
out << endl;
}
return out;
}
};
int main() {
Matrix a, b;
cout << "请输入矩阵a:" << endl;
cin >> a;
cout << "请输入矩阵b:" << endl;
cin >> b;
Matrix c = a + b;
cout << "矩阵a加b的结果为:" << endl;
cout << c;
return 0;
}
```
在上面的代码中,我们通过重载运算符“+”来实现矩阵相加。同时,我们也重载了输入和输出运算符“>>”和“<<”,使得我们可以方便地输入和输出矩阵。
阅读全文