Overloading Binary Operator using a Friend function: In this approach, the operator overloading function must precede with friend keyword, and declare a function class scope. Keeping in mind, the friend operator function takes two parameters in a binary operator, varies one parameter in a unary operator. All the working and implementation would same as the binary operator function except this function will be implemented outside of the class scope.
Let’s take the same example using the friend function.
#include <iostream>
using namespace std;
class space
{
int a, b, c;
public:
void getdata(int, int, int);
void display();
friend void operator-(space &ob);
};
void space::getdata(int x, int y, int z)
{
a = x;
b = y;
c = z;
};
void space::display()
{
cout << a << b << c;
};
void operator-(space &ob)
{
ob.a = -ob.a;
ob.b = -ob.b;
ob.c = -ob.c;
}
int main()
{
space s;
s.getdata(10,-12,9);
s.display();
-s;
cout<<endl;
s.display();
}
Post a Comment
If you have any doubts. Please Let me Know