Increment (++) And Decrement (--)Operator Overloading In C++
Operator overloading is
a feature in object-oriented
programming which allows a programmer to redefine a built-in operator to work
with user-defined data
types.
Overloading the increment operator
The operator symbol for
both prefix(++i) and postfix(i++) are
the same. Hence, we need two different function definitions to distinguish
between them.
Overloading the decrement operator
Fig: Increment (++) And Decrement (--)Operator Overloading In C++ |
Program:
#include<iostream.h>
#include<conio.h>
class
num
{
private:
int
n;
public:
void
getnum(int x)
{
n=x;
}
void
dispnum(void)
{
cout<<”value
of n is: “<<n;
}
void
operator++(void)
{
n=++n;
}
Void
operator—(void)
{
n=--n;
}
};
int
main()
{
num
a1;
a1.getnum(10);
++a1;
cout<<”after
increment-“;
a1.dispnum();
cout<<endl;
--a1;
cout<<”after
decrement-“;
a1.dispnum();
cout<<endl;
return
0;
}
Output:
After
increment- value of n is:11
After
decrement-value of n is:10
No comments:
Post a Comment