有两2*3规模的矩阵a和b,编写程序,求两个矩阵之和。重做插入运算符和提取运算符,使之能用于该矩阵的输入和输出。重载运算符“+”,使之能用于矩阵相加,如c=a+b.用完整地准确地c++语言表示
时间: 2024-05-01 17:22:06 浏览: 6
以下是实现上述功能的完整C++代码:
```c++
#include <iostream>
using namespace std;
class Matrix {
private:
int row, col;
int **data;
public:
Matrix(int r, int c) : row(r), col(c) {
data = new int*[row];
for (int i = 0; i < row; i++) {
data[i] = new int[col];
}
}
friend istream& operator >> (istream& in, Matrix& m) {
for (int i = 0; i < m.row; i++) {
for (int j = 0; j < m.col; j++) {
in >> m.data[i][j];
}
}
return in;
}
friend ostream& operator << (ostream& out, const Matrix& m) {
for (int i = 0; i < m.row; i++) {
for (int j = 0; j < m.col; j++) {
out << m.data[i][j] << " ";
}
out << endl;
}
return out;
}
Matrix operator + (const Matrix& m) const {
if (row != m.row || col != m.col) {
cerr << "Error: Matrix size does not match" << endl;
return Matrix(0, 0);
}
Matrix res(row, col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
res.data[i][j] = data[i][j] + m.data[i][j];
}
}
return res;
}
};
int main() {
Matrix a(2, 3), b(2, 3);
cout << "Input Matrix a:" << endl;
cin >> a;
cout << "Input Matrix b:" << endl;
cin >> b;
cout << "Matrix a:" << endl << a;
cout << "Matrix b:" << endl << b;
Matrix c = a + b;
cout << "Matrix c = a + b:" << endl << c;
return 0;
}
```
程序中定义了一个Matrix类,其中包含了矩阵的行列数和数据。为了方便输入和输出矩阵,重载了插入运算符和提取运算符。重载了加法运算符,使得可以直接使用“+”来计算矩阵的和。在主函数中,首先输入两个矩阵a和b,然后计算它们的和c,最后输出结果。