Search code examples
c++matrix-multiplication

C++ multiplication of 2 matrices


I am trying to multiply 2 matrices with the overloaded * operator and print the result. Although seems like I cannot have more than 1 argument to the overloaded function. How do I pass the two matrices to the overloaded function? Please see my implementation below.

#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;
}

Solution

  • 1. You are doing this operations:

    Class1 Matrix3 = Matrix1 * Matrix2;
    

    The return type of operator* is Class1, not void.

    2. When overloading an operator, the first operand is the this, and the second operand is the parameter you pass to the overloaded operator function. Hence, your definition should be:

      Class1 operator*(const Class1 &mat2)
    

    Now, you can perform the multiplication of the two objects, and return a new object of type Class1 that carries the result. So, you get:

     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;
    
     }