Index class with operator overloading
#include<iostream.h>
class index
{
private:
int value;
public:
index()
{
value=0;
}
int getindex()
{
return value;
}
void operator ++()
{
value=value+1;
}
};
void main()
{
index idx1,idx2;
cout <<"\n Index1 = "<< idex1.getindex();
cout <<"\n Index2 = "<< idx2.getindex();
++idx1; idx2++; idx2++;
cout <<"\nIndex1="<<idx1.getindex();
cout <<"\nIndex2="<<idx2.getindex();
}
Run
Index1=0
Index2=0
Index1=1
Index2=2
In main(), the statements
++idx1;
idx2++;
Invoke the overloaded function is ++. The term operator is a keyword and is preceded through the return type void. An operator to be overloaded is written instantly after the keyword operator. The above declaration informs the compiler to invoke the overloaded function ++ whenever the unary increment operators prefixed or post fixed to an object of the index class.
The variables idx1 and idx2 are he objects of the class index. An index value is advanced by using such statements like as ++idx1, idx++.