Answer to Question #254518 in C++ for Amit

Question #254518

Write a program to overload pre increment and post increment using friend function.


1
Expert's answer
2021-10-21T05:21:24-0400
#include <iostream>
using namespace std;

class Int {
public:
    Int(int x) : value(x) {}
    int getValue() const { return value; }
    void setValue(int x) { value = x; }


private:
    int value;

// prefix increment
friend Int& operator++(Int& i);
// postfix incrementfriend  Int& operator++(Int i);
friend Int operator++(Int& i, int);
};

Int& operator++(Int& i) 
{
    ++i.value;
    return i;
}

Int operator++(Int& i, int)
{
    Int res = i;
    i.value++;
    return res;
}

ostream& operator<<(ostream& os, Int i)
{
    os << i.getValue();
    return os;
}

int main()
{
    Int i1(1), i2(10);

    cout << "i1 = " << i1 << " i2 = " << i2 << endl;
    cout << "i1++ " << i1++ << " i2++ " << i2++ << endl;
    cout << "i1 = " << i1 << " i2 = " << i2 << endl;
    cout << "++i1 " << i1++ << " ++i2 " << i2++ << endl;
    cout << "i1 = " << i1 << " i2 = " << i2 << endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS