[英]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 old;
}
I have two questions: 我有两个问题:
1) what does “old” mean? 1)“旧”是什么意思?
2) ++(*this) is assumed to use the pre-increment, and the original pre-increment definition does not have argument. 2)假设++(* this)使用预增量,原始预增量定义没有参数。 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. 假设++(* this)使用预增量,而原始预增量定义没有参数。 However, it has *this here. 但是,这里有*。
*this
is not an argument. *this
不是一个论点。 The parentheses are not necessary, they are there for readability. 括号不是必需的,它们是为了便于阅读。
It's equivalent to ++*this
. 它等同于++*this
。
1) "old" is the value that "this" had before it was incremented. 1)“old”是“this”在递增之前所具有的值。 Post-increment is supposed to return that value. 后增量应该返回该值。
2) ++(*this) is equivalent to this->operator++() 2)++(* this)相当于this-> operator ++()
2) ++(*this) is assumed to use the pre-increment, and the original pre-increment definition does not have argument. 2)假设++(* this)使用预增量,原始预增量定义没有参数。 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. 未使用的int
参数只是区分增量前和后增量的黑客,因为operator++
可能意味着。 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: 使用函数调用语法调用运算符时,可以传递一个额外的int来区分这两者:
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). old
只是一个变量名(它不是关键字,如果那是你想知道的)。 It's used to save the previous value of the operand. 它用于保存操作数的先前值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.