Overloading Unary Operator as a Friend Function


#include <iostream.h>
#include<conio.h>
/*----------------------Class definition-------------------------*/
class sample
{
        int a;
        int b;
    public :
        sample() { }        // default empty constructor
        sample(int, int);

        // Overloaded unary minus as a friend
        friend void operator - (sample&);
        void print();
};
sample::sample(int x, int y)
{
    a = x;
    b = y;
}
void sample::print()
{
    cout << "a = " << a << "\n";
    cout << "b = " << b << "\n";
}
/*----------------------Definition ends here---------------------*/
void operator - (sample& x)    // friend function definition
{
    x.a = -x.a;
    x.b = -x.b;
}
void main(void)
{
    sample A(10,20);
    clrscr();
    cout << "Before the application of operator '-'(unary minus) :\n";
    A.print();
    -A;                // invoking operator function
    cout << "After the application of operator '-'(unary minus) :\n";
    A.print();
    operator -(A);    // another way of invoking - as a member function
    cout << "After the second application of operator '-'(unary minus) :\n";
    A.print();
    getch();
}

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|