一、题目描述
定义一个矩阵类MyMatrix,并且在类中进行运算符重定义,用*实现矩阵相乘。要求必须对运算符进行重载,如果用函数如multiply(matrix,matrix)去实现矩阵之间的运算一律记0分。
必须包含以下析构函数,其中n是矩阵的阶数,data是存放矩阵数据的二维动态数组:
MyMatrix::~MyMatrix() { // 释放空间 for (int i = 0; i < n; i++) { delete[] data[i]; } delete[] data; }
二、输入与输出
1.输入
第一行输入所需要的矩阵个数c;
第二行输入矩阵的阶数n,即矩阵是一个n*n的矩阵;
第三行开始依次输入c个矩阵.
2
2
1 2
1 2
1 0
1 1
2.输出
c个矩阵相乘的结果
3 2
3 2
三、参考代码
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Matrix
{
private:
int n;
vector<vector<int>> data;
public:
Matrix() {}
Matrix(int n1)
{
n = n1;
data.resize(n, vector<int>(n));
}
const vector<int>& operator[](const int q)const
{
return data[q];
}
vector<int>& operator[](const int q)
{
return data[q];
}
int operator()(int i, int j)const
{
return data[i][j];
}
Matrix operator*(const Matrix& p1) const
{
Matrix p2(n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
p2.data[i][j] += p1.data[k][j] * data[i][k];
}
}
}
return p2;
}
void print()
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (j == n - 1)
{
cout << data[i][j];
}
else
{
cout << data[i][j] << " ";
}
}
cout << endl;
}
}
};
int main()
{
int t, n;
cin >> t >> n;
Matrix p1(n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> p1[i][j];
}
}
t--;
while (t--)
{
Matrix p2(n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> p2[i][j];
}
}
p1 = p1 * p2;
}
p1.print();
return 0;
}