Overloading Binary '+' Operator as a friend function


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

        // Overloaded binary addition operator as a friend
        friend sample operator + (sample, 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---------------------*/
// Overloaded binary addition operator as a friend function
// Returns an object as a value of the addition
sample operator + (sample p, sample q)
{
    return sample(p.a+q.a, p.b+q.b);
}
void main(void)
{
    sample A(5,10), B(5,5), C;
    cout << "The result of the addition is :\n";
    C = A + B;    // invocation of the operator function
    C.print();
    cout << "\nSecond method of invocation of operator function-\n";
    cout << "The result of the addition is :\n";
    C = operator + (A,B);    // different way of invocation
    C.print();
}

0 comments:

Post a Comment

 
 
 
 


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