C++矩阵相乘(运算符重载)


一、题目描述

定义一个矩阵类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;
}


  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z1Jxxx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值