The prefix increment operator ++ can be overloaded for a class type by declaring a nonmember function operator with one argument of class type or a reference to class type, or by declaring a member function operator with no arguments.
In the following example, the increment operator is overloaded
in both ways:
// This example illustrates an overloaded prefix increment operator. class X { int a; public: operator++(); // member prefix increment operator }; class Y { /* ... */ }; operator++(Y& y); // nonmember prefix increment operator // Definitions of prefix increment operator functions // ... void main() { X x; Y y; ++x; // x.operator++ x.operator++(); // x.operator++ operator++(y); // nonmember operator++ ++y; // nonmember operator++ }
The postfix increment operator ++ can be overloaded for a class type by declaring a nonmember function operator operator++() with two arguments , the first having class type and the second having type int. Alternatively, you can declare a member function operator operator++() with one argument having type int. The compiler uses the int argument to distinguish between the prefix and postfix increment operators. For implicit calls, the default value is zero.
For example:
// This example illustrates an overloaded postfix increment operator. class X { int a; public: operator++(int); // member postfix increment operator }; operator++(X x, int i); // nonmember postfix increment operator // Definitions of postfix increment operator functions // ...
void main() { X x; x++; // x.operator++ // default zero is supplied by compiler x.operator++(0); // x.operator++ operator++(x,0); // nonmember operator++ }
The prefix and postfix decrement operators follow the same rules as their increment counterparts.