Monday, April 17, 2017

C++ code for Unary Operator Overloading(--) using Friend Function

This is the solution that increases an integer value by 1 by overloaded operator using Friend Function (T.U. 2072)

#include <iostream>

using namespace std;

class Decrement
{
    int a;
public:
    Decrement()
    {
        a=10;
    }
    Decrement(int x)
    {
        a=x;
    }
    friend operator++(Decrement &I,int); //Use & while using Friend Function
    friend operator++(Decrement &I);
    void print();
};

operator++(Decrement &I,int)
{
    I.a--;
}
operator++(Decrement &I)
{
    --I.a;
}

void Decrement::print()
{
    cout << endl << "a=" << a << endl ;
}

int main()
{
    Decrement D1;
    D1.print();
    D1--;
    D1.print();
    Decrement D2(100);
    D2.print();
    --D2;
    D2.print();
    return 0;
}

No comments:

Post a Comment