***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Monday, June 14, 2021

Overloading Binary operators

Binary operators are also used in overloading. They are also overloaded either using member functions or friend functions.

The member function requires one argument, whereas friend function requires two arguments because friend function is not a member function.

Syntax:-

returntype operator(classname)

{

-----------

}

 

Example. //Demonstrating binary operators in overloading

#include<iostream.h>

#include<conio.h>

class sample

{

private:

int n;

public:

sample()

{

 n=0;

}

sample(int k)

{

n=k;

}

void show(char *msg)

{

cout<<msg<<n<<endl;

}

sample operator+(sample s)

{

sample temp;

temp.n=n+s.n;

return temp;

}

sample operator-(sample s)

{

sample temp;

temp.n=n-s.n;

return temp;

}

sample operator*(sample s)

{

sample temp;

temp.n=n*s.n;

return temp;

}

};

void main()

{

clrscr();

sample s1(10),s2(20),s3;

s1.show("S1 : ");

s2.show("S2 : ");

s3=s1+s2;

s3.show("S1+S2 : ");

s3=s1-s2;

s3.show("S1-S2 : ");

s3=s1*s2;

s3.show(“S1*S2 : “);

getch();

}

No comments:

Post a Comment