[英]How to call postfix operator++?
Suppose I have the following code: 假设我有以下代码:
struct ReverseIterator : public Iterator {
ReverseIterator& operator++() {Iterator::operator--();}
ReverseIterator& operator--() {Iterator::operator++();}
ReverseIterator operator++(int) { /* ... */ }
ReverseIterator operator--(int) { /* ... */ }
}
How can I call the base class, Iterator, postfix increment/decrement operators? 如何调用基类,迭代器,后缀增量/减量运算符? I understand that to differentiate between pre- and post- fix, a temporary dummy variable is being passed.
我知道,为了区分修复前和修复后,会传递一个临时的虚拟变量。 If that is the case, can't I just call
Iteartor::operator++(1);
如果是这样,我不能只调用
Iteartor::operator++(1);
sine 1 is an integer? 正弦1是整数吗?
You can, but you shoud not to. 可以,但不要这样做。 Postfix inc/dec operator is usually must be implemented through the call of the corresponding prefix form.
Postfix inc / dec运算符通常必须通过调用相应的前缀形式来实现。 Moreover, value returned by base class operator is not compatible by type and there will be an error to return it as result of the derived class operator.
此外,基类运算符返回的值在类型上不兼容,并且派生类运算符将返回错误。
struct ReverseIterator : public Iterator {
ReverseIterator& operator++() {Iterator::operator--();}
ReverseIterator& operator--() {Iterator::operator++();}
ReverseIterator operator++(int)
{
ReverseIterator result = *this;
++(*this);
return result;
}
ReverseIterator operator--(int)
{
ReverseIterator result = *this;
--(*this);
return result;
}
}
I suppose you should read these questions: How to implement an STL-style iterator and avoid common pitfalls? 我想您应该阅读以下问题: 如何实现STL样式的迭代器并避免常见的陷阱?
How can I implement various iterator categories in an elegant and efficient way? 如何以一种优雅而有效的方式实现各种迭代器类别?
Yes, you may use those operators in a normal way, as in ++iterator
(prefix) and iterator++
(postfix), but you may call them directly, passing any argument. 是的,您可以按常规方式使用这些运算符,例如
++iterator
(前缀)和iterator++
(postfix),但是您可以直接调用它们,并传递任何参数。 If you are not actually using the formal parameter anywhere inside the definition, you may pass anything, typically 0
. 如果您实际上没有在定义内的任何地方使用形式参数,则可以传递任何东西,通常为
0
。
Sometimes the argument is used for incrementing by some value, like this: 有时,该参数用于增加某个值,例如:
i.operator++( 25 ); // Increment by 25.
But I wouldn't call that a good programming style. 但是我不会称其为良好的编程风格。 These operators aren't supposed to do this, and it's confusing.
这些运算符不应该这样做,这很令人困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.