How to Multiply two matrices using operator overloading in C++
Here in this tutorial, we will multiply two matrices using operator overlaoding in C++. C++ does not allow the use of operators on user-defined data types. Hence, we can use operator overloading to redefine operators.
Multiplication of two matrices using operator overloading in C++
Our approach will be to create a class named matrix and redefine the multiplication operator to multiply two matrices. First, we must have a good understanding of class and objects and operator overloading:
Here are some links to check out before starting this tutorial:
First, we will create a class called matrix and will create two functions in it. One to take input into a matrix object and another an operator which we will redefine. Operator overloading is basically redefining an operator to be able to do operations on user-defined classes.
include <bits/stdc++.h> using namespace std; int n; class matrix{ private: int arr[50][50]; public: void input(vector<vector<int>>& a); void operator *(matrix x); };
Then we will define the functions, first the “input” function.
void matrix::input(vector<vector<int>>& a){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ arr[i][j]=a[i][j]; } } }
Next, we will redefine the operator * declared in the class “matrix”. We have created a “result” matrix to store the product. Also, we have written the code to display the result matrix to simply print it after multiplication.
void matrix::operator *(matrix x){ int result[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ result[i][j]=0; for(int k=0;k<n;k++){ result[i][j]=result[i][j]+arr[i][k]*(x.arr[k][j]); } } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout<<result[i][j]<<" "; }cout<<endl; } }
Here is the full code:
#include <bits/stdc++.h> using namespace std; int n; class matrix{ private: int arr[50][50]; public: void input(vector<vector<int>>& a); void operator *(matrix x); }; void matrix::input(vector<vector<int>>& a){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ arr[i][j]=a[i][j]; } } } void matrix::operator *(matrix x){ int result[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ result[i][j]=0; for(int k=0;k<n;k++){ result[i][j]=result[i][j]+arr[i][k]*(x.arr[k][j]); } } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout<<result[i][j]<<" "; }cout<<endl; } } int main(){ n=3; vector<vector<int>>m1={{1,2,3},{4,5,6},{7,8,9}}; vector<vector<int>>m2={{1,2,3},{4,5,6},{7,8,9}}; matrix matrixobject1; matrix matrixobject2; matrixobject1.input(m1); matrixobject2.input(m2); matrixobject1*matrixobject2; }
Output:
Product matrix is: 30 36 42 66 81 96 102 126 150
Leave a Reply