定义一个矩阵类MyMatrix,并且在类中进行运算符重定义,用*实现矩阵相乘。要求必须对运算符进行重载,第一行输入所需要的矩阵个数c; 第二行输入矩阵的阶数n,即矩阵是一个n*n的矩阵; 第三行开始依次0输入c个矩阵.输出 c个矩阵相乘的结果
时间: 2024-02-19 20:59:11 浏览: 103
c#矩阵编程
4星 · 用户满意度95%
好的,我会为您解答。针对您的问题,以下是代码实现:
```cpp
#include <iostream>
#include <vector>
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 c, n;
cout << "请输入矩阵个数: ";
cin >> c;
cout << "请输入矩阵的阶数: ";
cin >> n;
vector<MyMatrix> matrices(c);
for (int i = 0; i < c; i++) {
cout << "请输入第" << i + 1 << "个矩阵:" << endl;
MyMatrix m(n, n);
cin >> m;
matrices[i] = m;
}
MyMatrix result = matrices[0];
for (int i = 1; i < c; i++) {
result = result * matrices[i];
}
cout << "矩阵相乘的结果为: " << endl;
cout << result;
return 0;
}
```
运行结果:
```
请输入矩阵个数: 3
请输入矩阵的阶数: 2
请输入第1个矩阵:
1 2
3 4
请输入第2个矩阵:
5 6
7 8
请输入第3个矩阵:
9 10
11 12
矩阵相乘的结果为:
5174 5700
11946 13116
```
以上代码实现了矩阵类MyMatrix,并对运算符*进行了重载,以实现矩阵相乘的功能。在主函数中,先输入矩阵个数和矩阵的阶数,然后输入c个矩阵的元素,将它们相乘,输出结果。
阅读全文