overloading pre-increment and post-increment
I saw an example about implementing pre-increment and post-increment, which claims that overloading pre-increment is able to be defined as
T& T ::operator++()
and overloading post-increment can be defined and implemented in terms of pre-incremet as follows
const T T::operator++(int){
const T old(*this);
++(*this);
return ol开发者_如何学God;
}
I have two questions:
1) what does “old” mean?
2) ++(*this) is assumed to use the pre-increment, and the original pre-increment definition does not have argument. However, it has *this here.
what does "old" mean?
The method is a post increment. The current value ("old value") is returned and then the value is incremented ("new value").
++(*this) is assumed to use the pre-increment, and the original pre-increment definition does not have argument. However, it has *this here.
*this
is not an argument. The parentheses are not necessary, they are there for readability.
It's equivalent to ++*this
.
1) "old" is the value that "this" had before it was incremented. Post-increment is supposed to return that value.
2) ++(*this) is equivalent to this->operator++()
2) ++(*this) is assumed to use the pre-increment, and the original pre-increment definition does not have argument. However, it has *this here.
++ is a unary operator, so it has an argument alright. Whenever you overload an operator as a member function, the first argument is the current object.
The unused int
parameter is but a hack to distinguish between pre- and post-increment, because operator++
can mean either. Post-increment does not really accept an integer*, it is just a (awkward) language construct.
You can also overload these operators as free functions:
struct T
{
int n;
};
T& operator++(T& t) { ++t.n; return t; }
T operator++(T& t, int) { T old(t); ++t; return old; }
int main()
{
T a;
T b = a++;
++b;
}
*under normal usage. When you invoke the operator using function call syntax, you can pass an additional int to distinguish between those two:
operator++(a); //calls-preincrement
operator++(b, 1); //calls post-increment
old
is simply a variable name (it's not a keyword, if that's what you were wondering). It's used to save the previous value of the operand.
精彩评论