重载前增量和后增量
我看到一个关于实现前自增和后自增的例子,它声称重载前自增可以定义为
T& T ::operator++()
,重载后自增可以用前自增来定义和实现,如下
const T T::operator++(int){
const T old(*this);
++(*this);
return old;
}
我有两个问题:
1)“老”是什么意思?
2) ++(*this) 假定使用预自增,并且原始预自增定义没有参数。然而,这里有*this。
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?
2) ++(*this) is assumed to use the pre-increment, and the original pre-increment definition does not have argument. However, it has *this here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该方法是后增量。返回当前值(“旧值”),然后该值递增(“新值”)。
*this
不是一个参数。括号不是必需的,它们是为了可读性而存在的。它相当于
++*this
。The method is a post increment. The current value ("old value") is returned and then the value is incremented ("new value").
*this
is not an argument. The parentheses are not necessary, they are there for readability.It's equivalent to
++*this
.1) “old”是“this”在增加之前的值。后增量应该返回该值。
2) ++(*this) 等价于 this->operator++()
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++()
++ 是一元运算符,因此它有一个参数。每当将运算符重载为成员函数时,第一个参数就是当前对象。
未使用的
int
参数只是区分前置增量和后置增量的一种技巧,因为operator++
可以表示其中任何一个。后递增并不真正接受整数*,它只是一种(尴尬的)语言构造。您还可以将这些运算符重载为自由函数:
*在正常使用情况下。当您使用函数调用语法调用运算符时,您可以传递一个附加 int 来区分这两者:
++ 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, becauseoperator++
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:
*under normal usage. When you invoke the operator using function call syntax, you can pass an additional int to distinguish between those two:
old
只是一个变量名(它不是关键字,如果您想知道的话)。它用于保存操作数的前一个值。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.