假设有两个均为3行3列的矩阵ml和m2,编写程序实现矩阵类Matrix,并重载运算符“+”、“>>”和“<<”,使之能用于矩阵m1和m2相加、输入和输出。
时间: 2024-05-22 15:16:00 浏览: 14
#include <iostream>
using namespace std;
class Matrix {
private:
int m[3][3];
public:
Matrix() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
m[i][j] = 0;
}
}
}
friend Matrix operator+(const Matrix& m1, const Matrix& m2) {
Matrix result;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result.m[i][j] = m1.m[i][j] + m2.m[i][j];
}
}
return result;
}
friend ostream& operator<<(ostream& os, const Matrix& m1) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
os << m1.m[i][j] << " ";
}
os << endl;
}
return os;
}
friend istream& operator>>(istream& is, Matrix& m1) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
is >> m1.m[i][j];
}
}
return is;
}
};
int main() {
Matrix m1, m2, m3;
cout << "请输入第一个矩阵:" << endl;
cin >> m1;
cout << "请输入第二个矩阵:" << endl;
cin >> m2;
m3 = m1 + m2;
cout << "两个矩阵相加的结果为:" << endl << m3;
return 0;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)