Matrix Operation using Operator Overloading

Write a program for four atrithmetic operations in matrix using operator overloading.

Questions by shakthisangi

Showing Answers 1 - 3 of 3 Answers

Sanket Akadkar

  • Sep 2nd, 2011
 

#include
#include

class matrix{
private:
int mat[5][5];
int row;
int column;
public:
matrix(int,int);
matrix(matrix&);
void getdata();
matrix operator-(matrix);
matrix operator+(matrix);
matrix operator*(matrix);
void display();
};

matrix::matrix(int r,int c)
{
cout<<"constructor to initiliaze no of rows and columns"< row=r;column=c;
}

matrix::matrix(matrix& m)
{
row=m.row;
column=m.column;

cout<<"Copy constructor"< for(int i=0;i {
for(int j=0;j {
mat[i][j]=m.mat[i][j];
}
}
}

void matrix::getdata()
{
cout<<"Value input:"< for(int i=0;i {
for(int j=0;j {
cout<<"Value("< cin>>mat[i][j];
}
}


}

matrix matrix::operator+(matrix a)
{
cout<<"Addition operator"<
matrix temp(row,column);

for(int i=0;i {
for(int j=0;j {
temp.mat[i][j]=mat[i][j]+a.mat[i][j];
}
}
return temp;
}

matrix matrix::operator-(matrix a)
{
cout<<"Subtraction operator"<
matrix temp(row,column);

for(int i=0;i {
for(int j=0;j {
temp.mat[i][j]=mat[i][j]-a.mat[i][j];
}
}
return temp;
}

matrix matrix::operator*(matrix a)
{
cout<<"Multiplaction operator"<
matrix temp(row,column);

for (int i=0;i {
for (int j=0;j {
temp.mat[i][j]=0;
for(int k=0;k {
temp.mat[i][j]=temp.mat[i][j]+(mat[i][k]*a.mat[k][j]);
}
}
}

return temp;
}

void matrix::display()
{
cout<<"The matrix is "< for(int i=0;i {
for(int j=0;j {
cout< }
cout< }
}

int main()
{
clrscr();
matrix m1(2,2),m2(2,2),m3(2,2);

m1.getdata();
m2.getdata();

m3=m1+m2;
m3.display();

m3=m1-m2;
m3.display();

m3=m1*m2;
m3.display();

getch();
return 0;
}

binoy

  • Aug 23rd, 2012
 

Code
  1. #include<iostream.h>

  2. #include<conio.h>

  3. /* function to check whether the order of matrix are same or not *//* function to read data for matrix*/"enter the number of rows

  4. ""enter the number of columns

  5. ""enter the elements of the matrix

  6. "/* function to add two matrix *//* function to subtract two matrix *//* function to display the contents of the matrix */" "/* main function */"Addition of matrices

  7. ""the result is

  8. ""subtraction of matrices

  9. ""The result is

  10. ""order of the input matrices is not identical

  11. "

  Was this answer useful?  Yes

JoolsL

  • Nov 19th, 2012
 

In both the above answers the op overloads should be using a const ref as input. You should have a (private) ctor that makes the matrix from the data, and should use RVO in the return.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions