Reputation: 493
I have this code:
class LazyStream {
ostream& output;
std::list<string> pending;
public:
//...
LazyStream operator++(int n = 0){
LazyStream other(output);
if (n>0) output << "<#" << n << ">";
output << pending.pop_front();
return other;
}
I do not understand the meaning of getting an int value for the operator++. I though it was just an indication that the operator is a suffix. How can the operator get a number? Can someone give an example?
Thanks
Upvotes: 3
Views: 325
Reputation: 55425
Apparently it's possible to pass that argument if you use function call syntax to call that operator. This code compiles cleanly with gcc and outputs 42
:
#include <iostream>
struct Stream {
Stream operator++(int n)
{
std::cout << n;
return *this;
}
};
int main()
{
Stream s;
s.operator++(42);
}
If I give it default value, it gives a warning (with -pedantic flag) that it cannot have one, though. It sort of makes sense, because if you also defined prefix increment, then the call s.operator++()
would be ambiguous. I didn't, however, find anything in the standard explicitly prohibiting the default value.
Upvotes: 2
Reputation: 154007
Well, it's the first time I've seen the int
defaulted.
As you point out, a "dummy" int
parameter is use to
distinguish the post-fix operator from the prefix. Except that
it's not really a dummy: when you write:
myVar ++;
and myVar
has a user defined postfix ++
, the compiler
actually calls it as:
myVar.operator++( 0 );
And there's nothing to stop you from writing:
myVar.operator++( 42 );
(Of course, having to do so, as in this case, sort of defeats the purpose of operator overloading.)
Upvotes: 3