用c++编写一个完整程序:有两个矩阵a和b,均为2行3列,求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加,如c=a+b。
时间: 2024-02-03 08:12:19 浏览: 40
下面是一个用C++编写的完整程序,实现了两个2行3列矩阵相加的功能:
```cpp
#include <iostream>
using namespace std;
class Matrix {
public:
Matrix() {}
Matrix(int a, int b, int c, int d, int e, int f) {
data[0][0] = a;
data[0][1] = b;
data[0][2] = c;
data[1][0] = d;
data[1][1] = e;
data[1][2] = f;
}
Matrix operator+(const Matrix& other) const {
Matrix result;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
result.data[i][j] = data[i][j] + other.data[i][j];
}
}
return result;
}
void print() const {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << data[i][j] << ' ';
}
cout << endl;
}
}
private:
int data[2][3];
};
int main() {
Matrix a(1, 2, 3, 4, 5, 6);
Matrix b(6, 5, 4, 3, 2, 1);
Matrix c = a + b;
c.print();
return 0;
}
```
程序中定义了一个Matrix类,表示一个2行3列的矩阵。类中有一个构造函数用来初始化矩阵,一个重载的加法运算符,以及一个打印矩阵的函数。在主函数中,我们分别定义了两个矩阵a和b,并将它们相加得到了矩阵c,最后打印出c的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)