Friend functions can be used to overload Prefix and Postfix forms of Increment/Decremnt operators in C++. Sample output and code are shown below.
Figure Below Shows a Sample Output
#include<iostream>
using namespace std;
class over_load
{
int n1,n2;
public:
void set(int x, int y)
{
n1=x;
n2=y;
}
void show()
{
cout<<"\nNumber 1 is "<<n1<<"\n";
cout<<"\nNumber 2 is "<<n2<<"\n";
}
friend over_load operator++(over_load &ob)
{
ob.n1++;
ob.n2++;
cout<<"\nPost Incremnt Operator Overloaded\n";
}
friend over_load operator++(over_load &ob, int x)
{
++ob.n1;
++ob.n2;
cout<<"\nPre Increment Operator Overloaded\n";
}
};
int main()
{
over_load ob1;
ob1.set(100,200);
cout<<"\nObejct ob1 Initially:\n";
ob1.show();
ob1++;
ob1.show();
++ob1;
ob1.show();
return 0;
}
Click here to download the C++ Program.
No comments:
Post a Comment