Overload Unary operators
Unary operators are operators that take only one operand. or that has only one operand.
Unary operators are ++ , - - etc
Here i have explain or overload ++ operator . BY this you can overload -- operator same step by step
#include <iostream>
using namespace std;
class counter
{
private:
int count;
public:
counter():count(0)
{}
counter(int c):count (c)
{}
void print () // if you want to take value from user then take a get() function
{
cout<<"counter is "<<count;
}
void operator ++ ()
{
++count;
}
};
void main ()
{
counter c1;
++c1;
c1.print();
}
......................................................................
if c2=++c1 , then compiler will complain.becaue we have define the ++ operator to have a return type void in the operator ++().while in assingnment statement it is being asked to return variable of type counter so you should have to do this thing
counter operator ++() // changing in program which is written above
{
++count;
counter temp;
temp.counter = count;
return temp;
}
};
void main ()
{
counter c1,c2;
++c1; // ++c1 for prefix form
c2=++c1;
operator return value
Returning via named object (temp).
.........................................................................
Now nameless temporary object
use this code in earlier program
counter operator ++()
{
++count;
return counter(count);
}
................................................................
we have earlier described about prefix form (++c1)
Now for finding post increment form that is (c1++)
you have to change something in earlier basic program for postfix form
if c1++
then
void operator ++( int ) // int is just a signal to the compiler to creat a postfix version of the operator
{
count++ ;
}
};
if c2 = c1++ , then you have to do
counter operator ++( int ) // int is just a signal to the compiler to creat a postfix version of the operator
{
return counter ( count++) ;
}
};