CPP - Friend Function

 

CPP

Friend Function



Fill in the blanks

1.Friend function restricts to access the private members from outside the class.

2.What is the keyword for friend function friend.

 

    Answer the following Question

                                                                              (10 marks)

1.Write a Program to add two Matrix using Friend Function

#include<iostream.h>

#include<conio.h>

class Matrix

{

   int a[3][3];

public:

   void getMatrix();

   void printMatrix();

   friend Matrix add(Matrix X,Matrix Y);

};

void Matrix::getMatrix()

{

   cout<<"Get Matrix elements one by one";

   for(int i=0;i<3;i++)

      for(int j=0;j<3;j++)

        cin>>a[i][j];

}

void Matrix::printMatrix()

{

   cout<<"Given Matrix is:\n";

   for(int i=0;i<3;i++)

   {

      for(int j=0;j<3;j++)

      {cout<<a[i][j]<<" ";}

      cout<<"\n";

   }

}

Matrix add(Matrix X,Matrix Y)

{

Matrix T;

cout<<"Addition of two matrices is \n";

for(int i=0;i<3;i++)

for(int j=0;j<3;j++)

T.a[i][j]=X.a[i][j]+Y.a[i][j];

return T;

}

void main()

{

   /*declares 3 object P,Q,R of type class Matrix*/

   Matrix P,Q,R;

   clrscr();

   P.getMatrix();

   Q.getMatrix();

   R=add(P,Q); /*alling friend add to add two matrices*/

   R.printMatrix(); /*for printing the result*/

   getch();

}

 

 

No comments:

Post a Comment