有两个矩阵a 和b ,均为2 行3 列。求两个矩阵之和。用成员函数重载运算符" + " ,使之能用于矩阵相加,如c=a+b。用友元函数重载运算符" - " ,使之能用于矩阵相减,如d=a-b。并以矩阵的形式输出c和d的值。
时间: 2024-05-05 12:21:37 浏览: 15
可以这样实现:
```c++
#include <iostream>
using namespace std;
class Matrix {
private:
int data[2][3];
public:
Matrix() {} // 默认构造函数
Matrix(int d[2][3]) { // 带参数的构造函数
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
data[i][j] = d[i][j];
}
}
}
Matrix operator+(const Matrix& matrix) { // 重载加号运算符
int d[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
d[i][j] = data[i][j] + matrix.data[i][j];
}
}
return Matrix(d);
}
friend Matrix operator-(const Matrix& m1, const Matrix& m2); // 声明友元函数
void print() { // 输出矩阵
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << data[i][j] << " ";
}
cout << endl;
}
}
};
Matrix operator-(const Matrix& m1, const Matrix& m2) { // 实现友元函数
int d[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
d[i][j] = m1.data[i][j] - m2.data[i][j];
}
}
return Matrix(d);
}
int main() {
int a[2][3] = { {1, 2, 3}, {4, 5, 6} };
int b[2][3] = { {7, 8, 9}, {10, 11, 12} };
Matrix m1(a), m2(b);
cout << "a + b = " << endl;
Matrix m3 = m1 + m2;
m3.print();
cout << "a - b = " << endl;
Matrix m4 = m1 - m2;
m4.print();
return 0;
}
```
输出结果为:
```
a + b =
8 10 12
14 16 18
a - b =
-6 -6 -6
-6 -6 -6
```
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)