qfedu-cpp-level/day5/homework/h3.cpp

62 lines
1.4 KiB
C++
Raw Normal View History

2023-08-14 17:20:39 +08:00
// 编写一个名为 Matrix 的类,表示矩阵。重载乘法运算符 *,使其能够执行两个矩阵的乘法操作。
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Matrix
{
private:
int row, col;
int **matrix;
public:
Matrix(int row, int col) : row(row), col(col)
{
matrix = new int *[row];
for (int i = 0; i < row; i++)
matrix[i] = new int[col];
}
~Matrix()
{
for (int i = 0; i < row; i++)
delete[] matrix[i];
delete[] matrix;
}
public:
Matrix operator*(const Matrix &m)
{
Matrix result(row, m.col);
for (int i = 0; i < row; i++)
for (int j = 0; j < m.col; j++)
for (int k = 0; k < col; k++)
result.matrix[i][j] += matrix[i][k] * m.matrix[k][j];
return result;
}
friend ostream &operator<<(ostream &out, const Matrix &m)
{
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
out << m.matrix[i][j] << " ";
out << endl;
}
return out;
}
friend istream &operator>>(istream &in, Matrix &m)
{
for (int i = 0; i < m.row; i++)
for (int j = 0; j < m.col; j++)
in >> m.matrix[i][j];
return in;
}
};
int main()
{
}