生成代码,要求重载流插入运算符“<<”和流提取运算符“>>”,使之能用于矩阵的输入和输出,用户直接输入矩阵
时间: 2024-05-04 19:21:36 浏览: 15
以下是重载流插入运算符“<<”和流提取运算符“>>”的示例代码,可以用于矩阵的输入和输出:
```c++
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
private:
int rows;
int cols;
vector<vector<int>> data;
public:
Matrix(int r, int c) : rows(r), cols(c), data(r, vector<int>(c)) {}
friend ostream& operator<<(ostream& os, const Matrix& mat) {
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
os << mat.data[i][j] << " ";
}
os << endl;
}
return os;
}
friend istream& operator>>(istream& is, Matrix& mat) {
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
is >> mat.data[i][j];
}
}
return is;
}
};
int main() {
int m, n;
cout << "Enter the number of rows and columns: ";
cin >> m >> n;
Matrix mat(m, n);
cout << "Enter the matrix elements: " << endl;
cin >> mat;
cout << "The matrix you entered is: " << endl;
cout << mat;
return 0;
}
```
在上面的示例代码中,我们定义了一个 Matrix 类来表示矩阵,并重载了流插入运算符“<<”和流提取运算符“>>”,使之能够用于矩阵的输入和输出。在主函数中,我们先让用户输入矩阵的行数和列数,然后创建一个 Matrix 对象,再让用户输入矩阵的元素,最后输出用户输入的矩阵。