Overloading Through Friend Functions
Overloading Through Friend Functions
The difference between operators using member functions and using friend is, friend function requires two argument explicitly.
Rules:
It requires two arguments. The symbol in the class and in the function should be same. Same operator can be overloaded for different data type argument list. Friend function cannot be overloaded with the given operators. Assignment = Function call () Class member class operator -> Subscripting operator []
#include<iostream.h> #include<conio.h> class complex { float x,y; public: void setdata(float r,float i) { x=r; y=i; } void print() { cout<<x<<"+"<<y<<"\n"; } friend complex operator+(complex,complex); }; complex operator+(complex c1,complex c2) { complex temp; temp.x=c1.x+c2.x; temp.y=c1.y+c2.y; return(temp); }
void main() { clrscr(); complex c1,c2,c; c1.setdata(12.4,3.2); c2.setdata(6.5,2.7); c=c1+c2; cout<<"\n the result is:"; c.print(); getch(); }