c++设计一个3行4列的矩阵类,重载运算符“+”和“-”,能实现矩阵类对象的加减运算;重载流插入运算符“《”和流提取运算符“》”,使之能用于矩阵的输入和输出
时间: 2023-09-24 15:11:30 浏览: 80
好的,下面是代码实现:
```c++
#include <iostream>
using namespace std;
class Matrix {
private:
int data[3][4];
public:
Matrix() {}
Matrix(int arr[][4]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
data[i][j] = arr[i][j];
}
}
}
friend Matrix operator+(const Matrix &a, const Matrix &b) {
Matrix c;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
c.data[i][j] = a.data[i][j] + b.data[i][j];
}
}
return c;
}
friend Matrix operator-(const Matrix &a, const Matrix &b) {
Matrix c;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
c.data[i][j] = a.data[i][j] - b.data[i][j];
}
}
return c;
}
friend ostream &operator<<(ostream &os, const Matrix &m) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
os << m.data[i][j] << " ";
}
os << endl;
}
return os;
}
friend istream &operator>>(istream &is, Matrix &m) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
is >> m.data[i][j];
}
}
return is;
}
};
int main() {
int a1[3][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int a2[3][4] = {{2, 3, 4, 5},
{6, 7, 8, 9},
{10, 11, 12, 13}};
Matrix m1(a1), m2(a2), m3, m4;
m3 = m1 + m2;
m4 = m1 - m2;
cout << "m1 + m2 =" << endl << m3 << endl;
cout << "m1 - m2 =" << endl << m4 << endl;
cout << "请输入一个3行4列的矩阵:" << endl;
cin >> m1;
cout << "你输入的矩阵为:" << endl << m1 << endl;
return 0;
}
```
这个矩阵类中重载了加减运算符和流插入提取运算符,可以进行矩阵的加减运算和输入输出。注意,这里重载的输出操作符是 `<<`,输入操作符是 `>>`。另外,为了方便起见,这里的矩阵大小是固定的,即3行4列。如果需要更一般化的矩阵类,可以考虑使用模板。
阅读全文