编写矩阵类: (1)类中定义矩阵类Matrix中的private类型的int型成员变量matrixArray[2][3]; (2)定义类成员函数InputData,对变量matrixArray进行以此赋值; (3)利用operator + 实现两个矩阵类对象的加法。 (4)重载流插入运算符“<<”和流提取运算符“>>”,使之能用于该矩阵的输入和输出。
时间: 2024-02-12 22:04:14 浏览: 37
好的,以下是该矩阵类Matrix的代码实现:
```cpp
#include <iostream>
using namespace std;
class Matrix {
private:
int matrixArray[2][3];
public:
void InputData() {
cout << "Please input the matrix data:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cin >> matrixArray[i][j];
}
}
}
Matrix operator+(const Matrix& m) {
Matrix result;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
result.matrixArray[i][j] = matrixArray[i][j] + m.matrixArray[i][j];
}
}
return result;
}
friend ostream& operator<<(ostream& os, const Matrix& m) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
os << m.matrixArray[i][j] << " ";
}
os << endl;
}
return os;
}
friend istream& operator>>(istream& is, Matrix& m) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
is >> m.matrixArray[i][j];
}
}
return is;
}
};
int main() {
Matrix m1, m2, m3;
m1.InputData();
m2.InputData();
m3 = m1 + m2;
cout << "m1 + m2 = " << endl << m3;
cout << "Please input the matrix data:" << endl;
cin >> m1;
cout << "The matrix you input is:" << endl << m1;
return 0;
}
```
在这个矩阵类中,我们定义了一个2行3列的矩阵,并实现了以下几个功能:
1. InputData函数:输入矩阵的数据;
2. operator+函数:实现两个矩阵对象的加法;
3. 重载运算符<< 和 >>:实现了对象的输入和输出。
在主函数中,我们首先定义了三个Matrix对象m1、m2和m3,然后通过调用InputData函数输入了m1和m2的数据,接着通过重载运算符+实现了矩阵的加法,并将结果存入m3中,最后输出了m3的结果。
另外,我们还通过重载运算符<< 和 >> 实现了对象的输入和输出,可以直接将对象作为输入输出流的参数,使代码更加简洁易懂。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)