Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
// Program to illustrate binary operator overloading (friend functions)


#include<iostream.h>
class matrix
{
     private:
     int element[10][10];
     int rows,cols;
     public:
     matrix(int,int);
     void input();
     void display();
     friend matrix operator + (matrix,matrix);
} ;

matrix::matrix(int r,int c)
{
     rows=r;
     cols=c;
}


void matrix::input()
{
     for(int i=0;i<rows;i++)
     for(int j=0;j<cols;j++)
     cin>>element[i][j];
}

void matrix:: display()
{
     for(int i=0;i<rows;i++)
     {
          for(int j=0;j<cols;j++)
          cout<<element[i][j]<<"\t";
          cout<<endl;
     }
}

matrix operator + (matrix m,matrix n)
{

     matrix temp(m.rows,m.cols);
     for(int i=0;i<m.rows;i++)
     for(int j=0;j<m.cols;j++)
     temp.element[i][j]=m.element[i][j] + n.element[i][j];
     return temp;
}



void main()
{

     matrix A(2,2),B(2,2),C(2,2);

     A.input();
     B.input();
     C=A+B;
     C.display();
}

Test data

1  2
3  4

3  4
5  6

Output
4  6
8  10