Write a program for Overloading a Unary Operator using Friend Function

/*
    Overloading a Unary Operator using Friend Function
    To Negate -
*/
#include<iostream>
using namespace std;

class Sample
{
    int a,b;

    public:
            void accept()
            {
                cout<<"\n\n Enter any two number: ";
                cin>>a>>b;
            }

            void display()
            {
                cout<<"\n\n A: "<<a;
                cout<<"\n B: "<<b;
            }

            friend void operator-( Sample &S);
};

void operator-(Sample &S)
{
    S.a=-S.a;
    S.b=-S.b;
}

int main()
{
    Sample S;

    S.accept();

    cout<<"\n\n Before Negate : ";
    S.display();

    -S;

    cout<<"\n\n After Negate : ";
    S.display();

    return 0;
}

Previous
Next Post »