为什么将int用作后递增运算符重载的参数? [英] Why use int as an argument for post-increment operator overload?

查看:92
本文介绍了为什么将int用作后递增运算符重载的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,这是重载后递增运算符的方法:

As I know here is the way to overload the post-increment operator:

const MyClass& MyClass::operator++(int);

为什么将int作为参数?

Why does it have int as an argument?

推荐答案

D& E , §11.5.3:

D&E, §11.5.3:

我考虑了一个明显的解决方案,在C ++中添加了关键字prefixpostfix [...] 但是,我从不喜欢新关键字的人那里收到了平常的愤怒之声.建议了几种不涉及新关键字的替代方法.例如:

I conisdered the obvious solution, adding the keywords prefix and postfix to C++ [ ... ] However I received the usual howl of outrage from people who dislike new keywords. Several alternatives that did not involve new keywords were suggested. For example:

class Ptr_to_X {
    X ++operator(); // prefix ++
    X operator++(); // postfix ++
};

class Ptr_to_X {
    X& operator++(); // postfix because it 
                     // returns a reference
    x operator();    // prefix because it
                     // doesn't return a reference
};

我认为前者太可爱了,而后者太微妙了.最终我选择了:

I considered the former too cute and the latter too subtle. Finally I settled on:

class Ptr_to_X {
    X operator++();     // prefix: no argument
    X operator++(int);  // postfix: because of the argument
};

这可能太可爱和太微妙了,但是它可以正常工作,不需要新的语法,并且有疯狂的逻辑.其他一元运算符是前缀,并且在定义为成员函数时不带任何参数. "odd"和未使用的伪int参数用于指示奇数后缀运算符.换句话说,在后缀情况下,++介于第一个(实际)操作数和第二个(虚拟)参数之间,因此为后缀.

This may be too cute and too subtle, but it works, requires no new syntax, and has a logic to the madness. Other unary operators are prefix and take no arguments when defined as member functions. The "odd" and unused dummy int argument is used to indicate the odd postfix operators. In other words, in the postfix case, ++ comes between the first (real) operand and the second (dummy) argument and is thus postfix.

这些解释是必需的,因为该机制是唯一的,因此有点疣.如果有选择的话,我可能会引入prefixpostfix关键字,但当时看来并不可行.

These explanations are needed because the mechanism is unique, and therefore a bit of a wart. Given a choice I would probably have introduced the prefix and postfix keywords, but that didn't appear feasible at the time.

这篇关于为什么将int用作后递增运算符重载的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆