有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加(如c=a+b)
时间: 2023-05-31 21:07:33 浏览: 90
矩阵a和b的和为c,可以使用如下的重载运算符“+”:
```cpp
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
public:
Matrix() {}
Matrix(int r, int c) {
resize(r, c);
}
void resize(int r, int c) {
data.resize(r);
for (int i = 0; i < r; ++i) {
data[i].resize(c);
}
}
friend Matrix operator+(const Matrix &a, const Matrix &b) {
Matrix c(a.row(), a.col());
for (int i = 0; i < a.row(); ++i) {
for (int j = 0; j < a.col(); ++j) {
c.data[i][j] = a.data[i][j] + b.data[i][j];
}
}
return c;
}
int row() const {
return data.size();
}
int col() const {
return data[0].size();
}
int &operator()(int row, int col) {
return data[row][col];
}
friend istream &operator>>(istream &in, Matrix &a) {
for (int i = 0; i < a.row(); ++i) {
for (int j = 0; j < a.col(); ++j) {
in >> a(i, j);
}
}
return in;
}
friend ostream &operator<<(ostream &out, const Matrix &a) {
for (int i = 0; i < a.row(); ++i) {
for (int j = 0; j < a.col(); ++j) {
out << a(i, j) << ' ';
}
out << endl;
}
return out;
}
private:
vector<vector<int>> data;
};
int main() {
Matrix a(2, 3), b(2, 3);
cin >> a >> b;
Matrix c = a + b;
cout << c << endl;
return 0;
}
```
阅读全文