Write a program to overload pre increment and post increment using friend function.
#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;
}
Comments
Leave a comment