【20分】D. 矩阵相乘(运算符重载)定义一个矩阵类MyMatrix,并且在类中进行运算符重定义,用*实现矩阵相乘。要求必须对运算符进行重载,如果用函数如multiply(matrix,matrix)去实现矩阵之间的运算一律记0分。
时间: 2024-02-19 20:59:10 浏览: 78
好的,我来为您解答。针对您的问题,以下是代码实现:
```cpp
#include <iostream>
using namespace std;
class MyMatrix {
private:
int row, col;
double *data;
public:
MyMatrix(int r = 0, int c = 0): row(r), col(c) {
data = new double[row * col];
for (int i = 0; i < row * col; i++) {
data[i] = 0;
}
}
MyMatrix(const MyMatrix &m) {
row = m.row;
col = m.col;
data = new double[row * col];
for (int i = 0; i < row * col; i++) {
data[i] = m.data[i];
}
}
~MyMatrix() {
delete []data;
}
MyMatrix &operator=(const MyMatrix &m) {
if (this == &m) {
return *this;
}
delete []data;
row = m.row;
col = m.col;
data = new double[row * col];
for (int i = 0; i < row * col; i++) {
data[i] = m.data[i];
}
return *this;
}
MyMatrix operator*(const MyMatrix &m) const {
if (col != m.row) {
cerr << "Error: matrix size mismatch!" << endl;
exit(1);
}
MyMatrix result(row, m.col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < m.col; j++) {
double sum = 0;
for (int k = 0; k < col; k++) {
sum += data[i * col + k] * m.data[k * m.col + j];
}
result.data[i * result.col + j] = sum;
}
}
return result;
}
friend istream &operator>>(istream &in, MyMatrix &m) {
for (int i = 0; i < m.row * m.col; i++) {
in >> m.data[i];
}
return in;
}
friend ostream &operator<<(ostream &out, const MyMatrix &m) {
for (int i = 0; i < m.row; i++) {
for (int j = 0; j < m.col; j++) {
out << m.data[i * m.col + j] << " ";
}
out << endl;
}
return out;
}
};
int main() {
int r1, c1, r2, c2;
cout << "请输入第一个矩阵的行数和列数: ";
cin >> r1 >> c1;
MyMatrix m1(r1, c1);
cout << "请输入第一个矩阵: " << endl;
cin >> m1;
cout << "请输入第二个矩阵的行数和列数: ";
cin >> r2 >> c2;
MyMatrix m2(r2, c2);
cout << "请输入第二个矩阵: " << endl;
cin >> m2;
MyMatrix result = m1 * m2;
cout << "矩阵相乘的结果为: " << endl;
cout << result;
return 0;
}
```
运行结果:
```
请输入第一个矩阵的行数和列数: 2 3
请输入第一个矩阵:
1 2 3
4 5 6
请输入第二个矩阵的行数和列数: 3 2
请输入第二个矩阵:
7 8
9 10
11 12
矩阵相乘的结果为:
58 64
139 154
```
以上代码实现了矩阵类MyMatrix,并对运算符*进行了重载,以实现矩阵相乘的功能。在主函数中,先输入两个矩阵的行列数和元素,然后将它们相乘,输出结果。
阅读全文