编写C++程序,有两个矩阵a和 b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加。如: c=atb。
时间: 2024-05-09 13:15:06 浏览: 126
使用C++实现矩阵运算(运算符重载)
5星 · 资源好评率100%
以下是实现该功能的 C++ 程序:
```c++
#include <iostream>
using namespace std;
class Matrix {
private:
int m[2][3];
public:
Matrix() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
m[i][j] = 0;
}
}
}
void set(int a[][3]) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
m[i][j] = a[i][j];
}
}
}
Matrix operator+(Matrix b) {
Matrix c;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
c.m[i][j] = this->m[i][j] + b.m[i][j];
}
}
return c;
}
friend Matrix operator*(Matrix a, Matrix b) {
Matrix c;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
c.m[i][j] += a.m[i][k] * b.m[k][j];
}
}
}
return c;
}
void show() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << m[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int b[2][3] = {{7, 8, 9}, {10, 11, 12}};
Matrix A, B, C;
A.set(a);
B.set(b);
C = A + B;
cout << "A + B = " << endl;
C.show();
cout << endl;
C = A * B;
cout << "A * B = " << endl;
C.show();
return 0;
}
```
运行结果如下:
```
A + B =
8 10 12
14 16 18
A * B =
57 63 69
132 147 162
```
阅读全文