Operator Function returning an object


#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 sample 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---------------------*/
sample operator - (sample x)    // friend function definition
{
    sample temp;
    temp.a = -x.a;
    temp.b = -x.b;
    return temp;
}
void main(void)
{
    sample A(5,10), B;
    clrscr();
    cout << "Result after first application of unary minus : \n";
    B = -A;             // invoking operator function
    B.print();
    cout << "Result after second application of unary minus : \n";
    B = operator - (B); // invoking operator function directly
    B.print();
    getch();
}

0 comments:

Post a Comment

 
 
 
 


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