C ++乘以2个矩阵

问题描述 投票:0回答:1

我试图将2个矩阵与重载的*运算符相乘并打印结果。虽然看起来我的重载函数不能超过1个参数。如何将两个矩阵传递给重载函数?请参阅下面的实施。

#include <iostream>
#include<string>
#include <vector>
using namespace std;



class Class1
{
public:
    vector<vector<int> > matrix;
    vector<vector<int> >  tmp;
    Class1(vector<vector<int> > p):matrix(move(p)){}

    //This function is used to perform the multiplication operation between two square matrices
    void operator*(const Class1 &mat1,const Class1 &mat2)
     {

        for(int i=0;i<4;i++)
        {
           for(int j=0;j<4;j++)
           {
//            matrix[i][j]=0;
              for(int k=0;k<4;k++)
              {
                 tmp[i][j]=tmp[i][j]+(mat2.matrix[i][k]*mat1.matrix[k][j]);
              }
           }
        }
//      return tmp;
     }

    void PrintVector()
    {
        for(int i=0;i<4;i++)
        {

            for(int j=0;j<4;j++)
            {
                cout<<tmp[i][j]<<"  ";
            }
            cout<<endl;
        }
        cout<<endl;
    }

};

int main()
{
    Class1 Matrix1 =   {{{ 21, 12, 13, 14 },
                       { 5, 6, 6, 8 },
                       { 9, 8, 7, 6 },
                       { 3, 2, 1, 1 } }};

    Class1 Matrix2 =   Matrix1;


    Class1 Matrix3 = Matrix1 * Matrix2;

    Matrix3.PrintVector();

    return 0;
}
c++ matrix-multiplication
1个回答
1
投票

你正在做这个操作:

Class1 Matrix3 = Matrix1 * Matrix2;

operator*的返回类型是Class1,而不是无效。

2.重载运算符时,第一个操作数是this,第二个操作数是传递给重载操作符函数的参数。因此,您的定义应该是:

  Class1 operator*(const Class1 &mat2)

现在,您可以执行两个对象的乘法运算,并返回一个包含结果的Class1类型的新对象。所以,你得到:

 Class1 operator*(const Class1 &mat2)
 {
     // Creating a reference for the `this` object to minimize changes in code
      Class1& mat1 = this;

     // perform the multiplication between mat1 and mat2
     for ( ... )
      .......

     // return the newly created object
     return tmp;

 }
© www.soinside.com 2019 - 2024. All rights reserved.